diff --git a/CodeGen/Generators/UnitsNetGen/ProjectGenerator.cs b/CodeGen/Generators/UnitsNetGen/ProjectGenerator.cs new file mode 100644 index 0000000000..4b4c0e0a02 --- /dev/null +++ b/CodeGen/Generators/UnitsNetGen/ProjectGenerator.cs @@ -0,0 +1,86 @@ +using System; +using CodeGen.Helpers; +using CodeGen.JsonTypes; + +namespace CodeGen.Generators.UnitsNetGen +{ + internal class ProjectGenerator : GeneratorBase + { + private readonly Quantity _quantity; + + public ProjectGenerator(Quantity quantity) + { + _quantity = quantity ?? throw new ArgumentNullException(nameof(quantity)); + } + + public string Generate() + { + Writer.WL($@"<Project Sdk=""Microsoft.NET.Sdk""> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET {_quantity.Name}</Title> + <Description>Adds {_quantity.Name} units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>{_quantity.Name.ToLower()} unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{HashGuid.ToHashGuid(_quantity.Name):B}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.{_quantity.Name}</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include=""Microsoft.SourceLink.GitHub"" Version=""1.1.1"" PrivateAssets=""All"" /> +<!-- <PackageReference Include=""UnitsNet.Core"" Version="""" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include=""..\..\UnitsNet.Core\UnitsNet.Core.csproj"" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include=""../../Docs/Images/logo-32.png"" Pack=""true"" PackagePath=""/"" /> + <None Include=""../../README.md"" Pack=""true"" PackagePath=""/"" /> + </ItemGroup> + +</Project>"); + + return Writer.ToString(); + } + } +} diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index b4c1faea65..240b614c00 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -220,6 +220,9 @@ private void GenerateStaticProperties() /// <inheritdoc cref=""IQuantity.QuantityInfo""/> public static QuantityInfo<{_unitEnumName}> Info {{ get; }} + /// <inheritdoc cref=""IQuantity.QuantityInfo""/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref=""BaseDimensions"" /> of this quantity. /// </summary> diff --git a/CodeGen/Generators/UnitsNetGen/SolutionGenerator.cs b/CodeGen/Generators/UnitsNetGen/SolutionGenerator.cs new file mode 100644 index 0000000000..6e684c21dd --- /dev/null +++ b/CodeGen/Generators/UnitsNetGen/SolutionGenerator.cs @@ -0,0 +1,64 @@ +using System; +using System.Text; +using CodeGen.Helpers; +using CodeGen.JsonTypes; + +namespace CodeGen.Generators.UnitsNetGen +{ + internal class SolutionGenerator : GeneratorBase + { + private readonly Quantity[] _quantities; + private readonly Guid _globalGuid = new("71d2836c-ed62-4b76-ba38-e15badcca916"); // Randomly generated guids. + private readonly Guid _solutionGuid = new("1f322b1f-1612-4e69-a31f-cb46bf87ec3e"); + + public SolutionGenerator(Quantity[] quantities) + { + _quantities = quantities; + } + + public string Generate() + { + StringBuilder sb = new(); + Writer.WL($@" +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29609.76 +MinimumVisualStudioVersion = 10.0.40219.1"); + + foreach (var quantity in _quantities) + { + var projectGuid = HashGuid.ToHashGuid(quantity.Name); + var projectName = $"UnitsNet.{quantity.Name}"; + Writer.WL($@" +Project(""{_globalGuid:B}"") = ""{projectName}"", ""UnitsNet.Modular\{projectName}\{projectName}.csproj"", ""{projectGuid:B}"" +EndProject"); + sb.Append($"{{{projectGuid}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n"); + sb.Append($"{{{projectGuid}}}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n"); + sb.Append($"{{{projectGuid}}}.Debug|Any CPU.Deploy.0 = Debug|Any CPU\r\n"); + sb.Append($"{{{projectGuid}}}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n"); + sb.Append($"{{{projectGuid}}}.Release|Any CPU.Build.0 = Release|Any CPU\r\n"); + sb.Append($"{{{projectGuid}}}.Release|Any CPU.Deploy.0 = Release|Any CPU\r\n"); + } + + Writer.WL(@"Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution"); + + Writer.WL(sb.ToString()); + + Writer.WL($@" EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {_solutionGuid:B} + EndGlobalSection +EndGlobal +"); + return Writer.ToString(); + } + } +} diff --git a/CodeGen/Generators/UnitsNetModularGen/ProjectGenerator.cs b/CodeGen/Generators/UnitsNetModularGen/ProjectGenerator.cs new file mode 100644 index 0000000000..088f8672db --- /dev/null +++ b/CodeGen/Generators/UnitsNetModularGen/ProjectGenerator.cs @@ -0,0 +1,86 @@ +using System; +using CodeGen.Helpers; +using CodeGen.JsonTypes; + +namespace CodeGen.Generators.UnitsNetModularGen +{ + internal class ProjectGenerator : GeneratorBase + { + private readonly Quantity _quantity; + + public ProjectGenerator(Quantity quantity) + { + _quantity = quantity ?? throw new ArgumentNullException(nameof(quantity)); + } + + public string Generate() + { + Writer.WL($@"<Project Sdk=""Microsoft.NET.Sdk""> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET {_quantity.Name}</Title> + <Description>Adds {_quantity.Name} units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>{_quantity.Name.ToLower()} unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{HashGuid.ToHashGuid(_quantity.Name):B}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.{_quantity.Name}</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include=""Microsoft.SourceLink.GitHub"" Version=""1.1.1"" PrivateAssets=""All"" /> +<!-- <PackageReference Include=""UnitsNet.Core"" Version="""" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include=""..\..\..\UnitsNet.Core\UnitsNet.Core.csproj"" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include=""../../../Docs/Images/logo-32.png"" Pack=""true"" PackagePath=""/"" /> + <None Include=""../../../README.md"" Pack=""true"" PackagePath=""/"" /> + </ItemGroup> + +</Project>"); + + return Writer.ToString(); + } + } +} diff --git a/CodeGen/Generators/UnitsNetModularGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetModularGen/QuantityGenerator.cs new file mode 100644 index 0000000000..29227316bf --- /dev/null +++ b/CodeGen/Generators/UnitsNetModularGen/QuantityGenerator.cs @@ -0,0 +1,1190 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Linq; +using CodeGen.Helpers; +using CodeGen.JsonTypes; + +namespace CodeGen.Generators.UnitsNetModularGen +{ + internal class QuantityGenerator : GeneratorBase + { + private readonly Quantity _quantity; + + private readonly bool _isDimensionless; + private readonly string _unitEnumName; + private readonly string _valueType; + private readonly Unit _baseUnit; + + public QuantityGenerator(Quantity quantity) + { + _quantity = quantity ?? throw new ArgumentNullException(nameof(quantity)); + + _baseUnit = quantity.Units.FirstOrDefault(u => u.SingularName == _quantity.BaseUnit) ?? + throw new ArgumentException($"No unit found with SingularName equal to BaseUnit [{_quantity.BaseUnit}]. This unit must be defined.", + nameof(quantity)); + + _valueType = quantity.ValueType; + _unitEnumName = $"{quantity.Name}Unit"; + + BaseDimensions baseDimensions = quantity.BaseDimensions; + _isDimensionless = baseDimensions is { L: 0, M: 0, T: 0, I: 0, Θ: 0, N: 0, J: 0 }; + } + + public string Generate() + { + Writer.WL(GeneratedFileHeader); + Writer.WL(@" +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{"); + Writer.WL($@" + /// <inheritdoc /> + /// <summary> + /// {_quantity.XmlDocSummary} + /// </summary>"); + + Writer.WLCondition(_quantity.XmlDocRemarks.HasText(), $@" + /// <remarks> + /// {_quantity.XmlDocRemarks} + /// </remarks>"); + + Writer.WLIfText(1, GetObsoleteAttributeOrNull(_quantity)); + Writer.W(@$" + [DataContract] + public readonly partial struct {_quantity.Name} : {(_quantity.GenerateArithmetic ? "IArithmeticQuantity" : "IQuantity")}<{_quantity.Name}, {_unitEnumName}, {_quantity.ValueType}>, "); + if (_quantity.ValueType == "decimal") + { + Writer.W("IDecimalQuantity, "); + } + + Writer.WL($"IEquatable<{_quantity.Name}>, IComparable, IComparable<{_quantity.Name}>, IConvertible, IFormattable"); + Writer.WL($@" + {{ + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = ""Value"", Order = 0)] + private readonly {_quantity.ValueType} _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = ""Unit"", Order = 1)] + private readonly {_unitEnumName}? _unit; +"); + GenerateStaticConstructor(); + GenerateInstanceConstructors(); + GenerateStaticProperties(); + GenerateProperties(); + GenerateConversionProperties(); + GenerateStaticMethods(); + GenerateStaticFactoryMethods(); + GenerateStaticParseMethods(); + GenerateArithmeticOperators(); + GenerateEqualityAndComparison(); + GenerateConversionMethods(); + GenerateToString(); + GenerateIConvertibleMethods(); + + Writer.WL($@" + }} +}}"); + return Writer.ToString(); + } + + private void GenerateStaticConstructor() + { + BaseDimensions baseDimensions = _quantity.BaseDimensions; + Writer.WL($@" + static {_quantity.Name}() + {{"); + Writer.WL(_isDimensionless ? $@" + BaseDimensions = BaseDimensions.Dimensionless;" : $@" + BaseDimensions = new BaseDimensions({baseDimensions.L}, {baseDimensions.M}, {baseDimensions.T}, {baseDimensions.I}, {baseDimensions.Θ}, {baseDimensions.N}, {baseDimensions.J});"); + + Writer.WL($@" + BaseUnit = {_unitEnumName}.{_quantity.BaseUnit}; + Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().ToArray(); + Zero = new {_quantity.Name}(0, BaseUnit); + Info = new QuantityInfo<{_unitEnumName}>(""{_quantity.Name}"", + new UnitInfo<{_unitEnumName}>[] + {{"); + + foreach (Unit unit in _quantity.Units) + { + BaseUnits? baseUnits = unit.BaseUnits; + if (baseUnits == null) + { + Writer.WL($@" + new UnitInfo<{_unitEnumName}>({_unitEnumName}.{unit.SingularName}, ""{unit.PluralName}"", BaseUnits.Undefined),"); + } + else + { + var baseUnitsCtorArgs = string.Join(", ", + new[] + { + baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null, + baseUnits.M != null ? $"mass: MassUnit.{baseUnits.M}" : null, + baseUnits.T != null ? $"time: DurationUnit.{baseUnits.T}" : null, + baseUnits.I != null ? $"current: ElectricCurrentUnit.{baseUnits.I}" : null, + baseUnits.Θ != null ? $"temperature: TemperatureUnit.{baseUnits.Θ}" : null, + baseUnits.N != null ? $"amount: AmountOfSubstanceUnit.{baseUnits.N}" : null, + baseUnits.J != null ? $"luminousIntensity: LuminousIntensityUnit.{baseUnits.J}" : null + }.Where(str => str != null)); + + Writer.WL($@" + new UnitInfo<{_unitEnumName}>({_unitEnumName}.{unit.SingularName}, ""{unit.PluralName}"", new BaseUnits({baseUnitsCtorArgs})),"); + } + } + + Writer.WL($@" + }}, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + }} +"); + } + + private void GenerateInstanceConstructors() + { + Writer.WL($@" + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name=""value"">The numeric value to construct this quantity with.</param> + /// <param name=""unit"">The unit representation to construct this quantity with.</param> + /// <exception cref=""ArgumentException"">If value is NaN or Infinity.</exception> + public {_quantity.Name}({_quantity.ValueType} value, {_unitEnumName} unit) + {{"); + Writer.WL(_quantity.ValueType == "double" + ? @" + _value = Guard.EnsureValidNumber(value, nameof(value));" + : @" + _value = value;"); + Writer.WL($@" + _unit = unit; + }} +"); + } + + private void GenerateStaticProperties() + { + Writer.WL($@" + #region Static Properties + + /// <summary> + /// The <see cref=""UnitConverter"" /> containing the default generated conversion functions for <see cref=""{_quantity.Name}"" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions {{ get; }} + + /// <inheritdoc cref=""IQuantity.QuantityInfo""/> + public static QuantityInfo<{_unitEnumName}> Info {{ get; }} + + /// <inheritdoc cref=""IQuantity.QuantityInfo""/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref=""BaseDimensions"" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions {{ get; }} + + /// <summary> + /// The base unit of {_quantity.Name}, which is {_quantity.BaseUnit}. All conversions go via this value. + /// </summary> + public static {_unitEnumName} BaseUnit {{ get; }} + + /// <summary> + /// All units of measurement for the {_quantity.Name} quantity. + /// </summary> + public static {_unitEnumName}[] Units {{ get; }} + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit {_quantity.BaseUnit}. + /// </summary> + public static {_quantity.Name} Zero {{ get; }} +"); + + if (_quantity.GenerateArithmetic) + { + Writer.WL($@" + /// <inheritdoc cref=""Zero""/> + public static {_quantity.Name} AdditiveIdentity => Zero; +"); + } + + Writer.WL($@" + #endregion + "); + } + + private void GenerateProperties() + { + Writer.WL($@" + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public {_valueType} Value => _value; +"); + + Writer.WL(@" + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; +"); + // Need to provide explicit interface implementation for decimal quantities like Information + if (_quantity.ValueType == "decimal") + Writer.WL(@" + /// <inheritdoc cref=""IDecimalQuantity.Value""/> + decimal IDecimalQuantity.Value => _value; +"); + + Writer.WL($@" + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public {_unitEnumName} Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<{_unitEnumName}> QuantityInfo => Info; + + /// <inheritdoc cref=""IQuantity.QuantityInfo""/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref=""BaseDimensions"" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => {_quantity.Name}.BaseDimensions; + + #endregion +"); + } + + private void GenerateConversionProperties() + { + Writer.WL(@" + #region Conversion Properties +"); + foreach (Unit unit in _quantity.Units) + { + if (unit.SkipConversionGeneration) continue; + + Writer.WL($@" + /// <summary> + /// Gets a <see cref=""{_quantity.ValueType}""/> value of this quantity converted into <see cref=""{_unitEnumName}.{unit.SingularName}""/> + /// </summary>"); + Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); + Writer.WL($@" + public {_quantity.ValueType} {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); +"); + } + + Writer.WL(@" + + #endregion +"); + } + + private void GenerateStaticMethods() + { + Writer.WL($@" + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref=""UnitConverter""/> instance. + /// </summary> + /// <param name=""unitConverter"">The <see cref=""UnitConverter""/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + {{ + // Register in unit converter: {_quantity.Name}Unit -> BaseUnit"); + + foreach (Unit unit in _quantity.Units) + { + if (unit.SingularName == _quantity.BaseUnit) continue; + + Writer.WL($@" + unitConverter.SetConversionFunction<{_quantity.Name}>({_quantity.Name}Unit.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity.ToUnit({_unitEnumName}.{_quantity.BaseUnit}));"); + } + + Writer.WL(); + Writer.WL($@" + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity); + + // Register in unit converter: BaseUnit -> {_quantity.Name}Unit"); + + foreach (Unit unit in _quantity.Units) + { + if (unit.SingularName == _quantity.BaseUnit) continue; + + Writer.WL($@" + unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_quantity.Name}Unit.{unit.SingularName}, quantity => quantity.ToUnit({_quantity.Name}Unit.{unit.SingularName}));"); + } + + Writer.WL($@" + }} + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + {{"); + foreach(Unit unit in _quantity.Units) + { + foreach(Localization localization in unit.Localization) + { + // All units must have a unit abbreviation, so fallback to "" for units with no abbreviations defined in JSON + var abbreviationParams = localization.Abbreviations.Any() ? + string.Join(", ", localization.Abbreviations.Select(abbr => $@"""{abbr}""")) : + $@""""""; + + Writer.WL($@" + unitAbbreviationsCache.PerformAbbreviationMapping({_unitEnumName}.{unit.SingularName}, new CultureInfo(""{localization.Culture}""), false, {unit.AllowAbbreviationLookup.ToString().ToLower()}, new string[]{{{abbreviationParams}}});"); + } + } + + Writer.WL($@" + }} + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name=""unit"">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation({_unitEnumName} unit) + {{ + return GetAbbreviation(unit, null); + }} + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name=""unit"">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name=""provider"">Format to use for localization. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + public static string GetAbbreviation({_unitEnumName} unit, IFormatProvider? provider) + {{ + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + }} + + #endregion +"); + } + + private void GenerateStaticFactoryMethods() + { + Writer.WL(@" + #region Static Factory Methods +"); + foreach (Unit unit in _quantity.Units) + { + if (unit.SkipConversionGeneration) continue; + + var valueParamName = unit.PluralName.ToLowerInvariant(); + Writer.WL($@" + /// <summary> + /// Creates a <see cref=""{_quantity.Name}""/> from <see cref=""{_unitEnumName}.{unit.SingularName}""/>. + /// </summary> + /// <exception cref=""ArgumentException"">If value is NaN or Infinity.</exception>"); + Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); + Writer.WL($@" + public static {_quantity.Name} From{unit.PluralName}(QuantityValue {valueParamName}) + {{ + {_valueType} value = ({_valueType}) {valueParamName}; + return new {_quantity.Name}(value, {_unitEnumName}.{unit.SingularName}); + }} +"); + } + + Writer.WL($@" + /// <summary> + /// Dynamically convert from value and unit enum <see cref=""{_unitEnumName}"" /> to <see cref=""{_quantity.Name}"" />. + /// </summary> + /// <param name=""value"">Value to convert from.</param> + /// <param name=""fromUnit"">Unit to convert from.</param> + /// <returns>{_quantity.Name} unit value.</returns> + public static {_quantity.Name} From(QuantityValue value, {_unitEnumName} fromUnit) + {{ + return new {_quantity.Name}(({_valueType})value, fromUnit); + }} + + #endregion +"); + } + + private void GenerateStaticParseMethods() + { + Writer.WL($@" + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format ""<quantity> <unit>"". + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <example> + /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); + /// </example> + /// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception> + /// <exception cref=""ArgumentException""> + /// Expected string to have one or two pairs of quantity and unit in the format + /// ""<quantity> <unit>"". Eg. ""5.5 m"" or ""1ft 2in"" + /// </exception> + /// <exception cref=""AmbiguousUnitParseException""> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse(""1 cup"") will throw, because it can refer to any of + /// <see cref=""VolumeUnit.MetricCup"" />, <see cref=""VolumeUnit.UsLegalCup"" /> and <see cref=""VolumeUnit.UsCustomaryCup"" />. + /// </exception> + /// <exception cref=""UnitsNetException""> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref=""UnitsNetException"" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static {_quantity.Name} Parse(string str) + {{ + return Parse(str, null); + }} + + /// <summary> + /// Parse a string with one or two quantities of the format ""<quantity> <unit>"". + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <example> + /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); + /// </example> + /// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception> + /// <exception cref=""ArgumentException""> + /// Expected string to have one or two pairs of quantity and unit in the format + /// ""<quantity> <unit>"". Eg. ""5.5 m"" or ""1ft 2in"" + /// </exception> + /// <exception cref=""AmbiguousUnitParseException""> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse(""1 cup"") will throw, because it can refer to any of + /// <see cref=""VolumeUnit.MetricCup"" />, <see cref=""VolumeUnit.UsLegalCup"" /> and <see cref=""VolumeUnit.UsCustomaryCup"" />. + /// </exception> + /// <exception cref=""UnitsNetException""> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref=""UnitsNetException"" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + public static {_quantity.Name} Parse(string str, IFormatProvider? provider) + {{ + return QuantityParser.Default.Parse<{_quantity.Name}, {_unitEnumName}>( + str, + provider, + From); + }} + + /// <summary> + /// Try to parse a string with one or two quantities of the format ""<quantity> <unit>"". + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <param name=""result"">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); + /// </example> + public static bool TryParse(string? str, out {_quantity.Name} result) + {{ + return TryParse(str, null, out result); + }} + + /// <summary> + /// Try to parse a string with one or two quantities of the format ""<quantity> <unit>"". + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <param name=""result"">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse(""5.5 m"", new CultureInfo(""en-US"")); + /// </example> + /// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out {_quantity.Name} result) + {{ + return QuantityParser.Default.TryParse<{_quantity.Name}, {_unitEnumName}>( + str, + provider, + From, + out result); + }} + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <example> + /// Length.ParseUnit(""m"", new CultureInfo(""en-US"")); + /// </example> + /// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception> + /// <exception cref=""UnitsNetException"">Error parsing string.</exception> + public static {_unitEnumName} ParseUnit(string str) + {{ + return ParseUnit(str, null); + }} + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + /// <example> + /// Length.ParseUnit(""m"", new CultureInfo(""en-US"")); + /// </example> + /// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception> + /// <exception cref=""UnitsNetException"">Error parsing string.</exception> + public static {_unitEnumName} ParseUnit(string str, IFormatProvider? provider) + {{ + return UnitParser.Default.Parse<{_unitEnumName}>(str, provider); + }} + + /// <inheritdoc cref=""TryParseUnit(string,IFormatProvider,out UnitsNet.Units.{_unitEnumName})""/> + public static bool TryParseUnit(string str, out {_unitEnumName} unit) + {{ + return TryParseUnit(str, null, out unit); + }} + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param> + /// <param name=""unit"">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit(""m"", new CultureInfo(""en-US"")); + /// </example> + /// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out {_unitEnumName} unit) + {{ + return UnitParser.Default.TryParse<{_unitEnumName}>(str, provider, out unit); + }} + + #endregion +"); + } + + private void GenerateArithmeticOperators() + { + if (!_quantity.GenerateArithmetic) return; + + // Logarithmic units required different arithmetic + if (_quantity.Logarithmic) + { + GenerateLogarithmicArithmeticOperators(); + return; + } + + Writer.WL($@" + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static {_quantity.Name} operator -({_quantity.Name} right) + {{ + return new {_quantity.Name}(-right.Value, right.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from adding two <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator +({_quantity.Name} left, {_quantity.Name} right) + {{ + return new {_quantity.Name}(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from subtracting two <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator -({_quantity.Name} left, {_quantity.Name} right) + {{ + return new {_quantity.Name}(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from multiplying value and <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator *({_valueType} left, {_quantity.Name} right) + {{ + return new {_quantity.Name}(left * right.Value, right.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from multiplying value and <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator *({_quantity.Name} left, {_valueType} right) + {{ + return new {_quantity.Name}(left.Value * right, left.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from dividing <see cref=""{_quantity.Name}""/> by value.</summary> + public static {_quantity.Name} operator /({_quantity.Name} left, {_valueType} right) + {{ + return new {_quantity.Name}(left.Value / right, left.Unit); + }} + + /// <summary>Get ratio value from dividing <see cref=""{_quantity.Name}""/> by <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.ValueType} operator /({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.{_baseUnit.PluralName} / right.{_baseUnit.PluralName}; + }} + + #endregion +"); + } + + private void GenerateLogarithmicArithmeticOperators() + { + var scalingFactor = _quantity.LogarithmicScalingFactor; + // Most logarithmic operators need a simple scaling factor of 10. However, certain units such as voltage ratio need to use 20 instead. + var x = (10 * scalingFactor).ToString(); + Writer.WL($@" + #region Logarithmic Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static {_quantity.Name} operator -({_quantity.Name} right) + {{ + return new {_quantity.Name}(-right.Value, right.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic addition of two <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator +({_quantity.Name} left, {_quantity.Name} right) + {{ + // Logarithmic addition + // Formula: {x} * log10(10^(x/{x}) + 10^(y/{x})) + return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, left.Value / {x}) + Math.Pow(10, right.ToUnit(left.Unit).Value / {x})), left.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic subtraction of two <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator -({_quantity.Name} left, {_quantity.Name} right) + {{ + // Logarithmic subtraction + // Formula: {x} * log10(10^(x/{x}) - 10^(y/{x})) + return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, left.Value / {x}) - Math.Pow(10, right.ToUnit(left.Unit).Value / {x})), left.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic multiplication of value and <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator *({_valueType} left, {_quantity.Name} right) + {{ + // Logarithmic multiplication = addition + return new {_quantity.Name}(left + right.Value, right.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic multiplication of value and <see cref=""{_quantity.Name}""/>.</summary> + public static {_quantity.Name} operator *({_quantity.Name} left, double right) + {{ + // Logarithmic multiplication = addition + return new {_quantity.Name}(left.Value + ({_valueType})right, left.Unit); + }} + + /// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic division of <see cref=""{_quantity.Name}""/> by value.</summary> + public static {_quantity.Name} operator /({_quantity.Name} left, double right) + {{ + // Logarithmic division = subtraction + return new {_quantity.Name}(left.Value - ({_valueType})right, left.Unit); + }} + + /// <summary>Get ratio value from logarithmic division of <see cref=""{_quantity.Name}""/> by <see cref=""{_quantity.Name}""/>.</summary> + public static double operator /({_quantity.Name} left, {_quantity.Name} right) + {{ + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + }} + + #endregion +" ); + } + + private void GenerateEqualityAndComparison() + { + Writer.WL($@" + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.Value <= right.ToUnit(left.Unit).Value; + }} + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.Value >= right.ToUnit(left.Unit).Value; + }} + + /// <summary>Returns true if less than.</summary> + public static bool operator <({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.Value < right.ToUnit(left.Unit).Value; + }} + + /// <summary>Returns true if greater than.</summary> + public static bool operator >({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.Value > right.ToUnit(left.Unit).Value; + }} + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref=""Equals({_quantity.Name}, {_valueType}, ComparisonType)""/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete(""Consider using Equals(Angle, {_valueType}, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance."")] + public static bool operator ==({_quantity.Name} left, {_quantity.Name} right) + {{ + return left.Equals(right); + }} + + /// <summary>Indicates strict inequality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref=""Equals({_quantity.Name}, {_valueType}, ComparisonType)""/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete(""Consider using Equals(Angle, {_valueType}, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance."")] + public static bool operator !=({_quantity.Name} left, {_quantity.Name} right) + {{ + return !(left == right); + }} + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref=""Equals({_quantity.Name}, {_valueType}, ComparisonType)""/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete(""Consider using Equals(Angle, {_valueType}, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance."")] + public override bool Equals(object? obj) + {{ + if (obj is null || !(obj is {_quantity.Name} otherQuantity)) + return false; + + return Equals(otherQuantity); + }} + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref=""Equals({_quantity.Name}, {_valueType}, ComparisonType)""/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete(""Consider using Equals(Angle, {_valueType}, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance."")] + public bool Equals({_quantity.Name} other) + {{ + return new {{ Value, Unit }}.Equals(new {{ other.Value, other.Unit }}); + }} + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref=""{_quantity.Name}""/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name=""obj"">An object to compare with this instance.</param> + /// <exception cref=""T:System.ArgumentException""> + /// <paramref name=""obj"" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type=""table""> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name=""obj"" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name=""obj"" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name=""obj"" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + {{ + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is {_quantity.Name} otherQuantity)) throw new ArgumentException(""Expected type {_quantity.Name}."", nameof(obj)); + + return CompareTo(otherQuantity); + }} + + /// <summary>Compares the current <see cref=""{_quantity.Name}""/> with another <see cref=""{_quantity.Name}""/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name=""other"">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type=""table""> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name=""other"" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name=""other"" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name=""other"" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo({_quantity.Name} other) + {{ + return _value.CompareTo(other.ToUnit(this.Unit).Value); + }} + + /// <summary> + /// <para> + /// Compare equality to another {_quantity.Name} within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name=""other""/> as a percentage of this quantity's value. <paramref name=""other""/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name=""other""/> as a fixed number in this quantity's unit. <paramref name=""other""/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using {_valueType} internally. + /// </para> + /// </summary> + /// <param name=""other"">The other quantity to compare to.</param> + /// <param name=""tolerance"">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name=""comparisonType"">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals({_quantity.Name} other, {_quantity.ValueType} tolerance, ComparisonType comparisonType) + {{ + if (tolerance < 0) + throw new ArgumentOutOfRangeException(""tolerance"", ""Tolerance must be greater than or equal to 0.""); + + {_quantity.ValueType} thisValue = this.Value; + {_quantity.ValueType} otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + }} + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current {_quantity.Name}.</returns> + public override int GetHashCode() + {{ + return new {{ Info.Name, Value, Unit }}.GetHashCode(); + }} + + #endregion +"); + } + + private void GenerateConversionMethods() + { + Writer.WL($@" + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name=""unit"" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public {_quantity.ValueType} As({_unitEnumName} unit) + {{ + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + }} +"); + + if (_quantity.ValueType == "decimal") + { + Writer.WL($@" + + double IQuantity<{_unitEnumName}>.As({_unitEnumName} unit) + {{ + return (double)As(unit); + }} +"); + } + + Writer.WL($@" + /// <inheritdoc /> + double IQuantity.As(Enum unit) + {{ + if (!(unit is {_unitEnumName} typedUnit)) + throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); + + return (double)As(typedUnit); + }} + + /// <summary> + /// Converts this {_quantity.Name} to another {_quantity.Name} with the unit representation <paramref name=""unit"" />. + /// </summary> + /// <param name=""unit"">The unit to convert to.</param> + /// <returns>A {_quantity.Name} with the specified unit.</returns> + public {_quantity.Name} ToUnit({_unitEnumName} unit) + {{ + return ToUnit(unit, DefaultConversionFunctions); + }} + + /// <summary> + /// Converts this <see cref=""{_quantity.Name}""/> to another <see cref=""{_quantity.Name}""/> using the given <paramref name=""unitConverter""/> with the unit representation <paramref name=""unit"" />. + /// </summary> + /// <param name=""unit"">The unit to convert to.</param> + /// <param name=""unitConverter"">The <see cref=""UnitConverter""/> to use for the conversion.</param> + /// <returns>A {_quantity.Name} with the specified unit.</returns> + public {_quantity.Name} ToUnit({_unitEnumName} unit, UnitConverter unitConverter) + {{ + if (TryToUnit(unit, out var converted)) + {{ + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + }} + else if (unitConverter.TryGetConversionFunction((typeof({_quantity.Name}), Unit, typeof({_quantity.Name}), unit), out var conversionFunction)) + {{ + // See if the unit converter has an extensibility conversion registered. + return ({_quantity.Name})conversionFunction(this); + }} + else if (Unit != BaseUnit) + {{ + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + }} + else + {{ + // No possible conversion + throw new NotImplementedException($""Can not convert {{Unit}} to {{unit}}.""); + }} + }} + + /// <summary> + /// Attempts to convert this <see cref=""{_quantity.Name}""/> to another <see cref=""{_quantity.Name}""/> with the unit representation <paramref name=""unit"" />. + /// </summary> + /// <param name=""unit"">The unit to convert to.</param> + /// <param name=""converted"">The converted <see cref=""{_quantity.Name}""/> in <paramref name=""unit""/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit({_quantity.Name}Unit unit, [NotNullWhen(true)] out {_quantity.Name}? converted) + {{ + if (Unit == unit) + {{ + converted = this; + return true; + }} + + {_quantity.Name}? convertedOrNull = (Unit, unit) switch + {{ + // {_quantity.Name}Unit -> BaseUnit"); + + foreach (Unit unit in _quantity.Units) + { + if (unit.SingularName == _quantity.BaseUnit) continue; + + var func = unit.FromUnitToBaseFunc.Replace("{x}", "_value"); + Writer.WL($@" + ({_quantity.Name}Unit.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}) => new {_quantity.Name}({func}, {_unitEnumName}.{_quantity.BaseUnit}),"); + } + + Writer.WL(); + Writer.WL($@" + + // BaseUnit -> {_quantity.Name}Unit"); + foreach(Unit unit in _quantity.Units) + { + if (unit.SingularName == _quantity.BaseUnit) continue; + + var func = unit.FromBaseToUnitFunc.Replace("{x}", "_value"); + Writer.WL($@" + ({_unitEnumName}.{_quantity.BaseUnit}, {_quantity.Name}Unit.{unit.SingularName}) => new {_quantity.Name}({func}, {_quantity.Name}Unit.{unit.SingularName}),"); + } + + Writer.WL(); + Writer.WL($@" + _ => null + }}; + + if (convertedOrNull is null) + {{ + converted = default; + return false; + }} + + converted = convertedOrNull.Value; + return true; + }} + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + {{ + if (!(unit is {_unitEnumName} typedUnit)) + throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + }} + + /// <inheritdoc /> + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit) => ToUnit(unit); + + #endregion +"); + } + + private void GenerateToString() + { + Writer.WL($@" + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + {{ + return ToString(""g""); + }} + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name=""provider"">Format to use for localization and number formatting. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + public string ToString(IFormatProvider? provider) + {{ + return ToString(""g"", provider); + }} + + /// <inheritdoc cref=""QuantityFormatter.Format{{TUnitType}}(IQuantity{{TUnitType}}, string, IFormatProvider)""/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref=""CultureInfo.CurrentCulture"" />. + /// </summary> + /// <param name=""format"">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + {{ + return ToString(format, CultureInfo.CurrentCulture); + }} + + /// <inheritdoc cref=""QuantityFormatter.Format{{TUnitType}}(IQuantity{{TUnitType}}, string, IFormatProvider)""/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref=""CultureInfo.CurrentCulture"" /> if null. + /// </summary> + /// <param name=""format"">The format string.</param> + /// <param name=""provider"">Format to use for localization and number formatting. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + {{ + return QuantityFormatter.Format<{_unitEnumName}>(this, format, provider); + }} + + #endregion +" ); + } + + private void GenerateIConvertibleMethods() + { + Writer.WL($@" + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + {{ + return TypeCode.Object; + }} + + bool IConvertible.ToBoolean(IFormatProvider? provider) + {{ + throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to bool is not supported.""); + }} + + byte IConvertible.ToByte(IFormatProvider? provider) + {{ + return Convert.ToByte(_value); + }} + + char IConvertible.ToChar(IFormatProvider? provider) + {{ + throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to char is not supported.""); + }} + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + {{ + throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to DateTime is not supported.""); + }} + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + {{ + return Convert.ToDecimal(_value); + }} + + double IConvertible.ToDouble(IFormatProvider? provider) + {{ + return Convert.ToDouble(_value); + }} + + short IConvertible.ToInt16(IFormatProvider? provider) + {{ + return Convert.ToInt16(_value); + }} + + int IConvertible.ToInt32(IFormatProvider? provider) + {{ + return Convert.ToInt32(_value); + }} + + long IConvertible.ToInt64(IFormatProvider? provider) + {{ + return Convert.ToInt64(_value); + }} + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + {{ + return Convert.ToSByte(_value); + }} + + float IConvertible.ToSingle(IFormatProvider? provider) + {{ + return Convert.ToSingle(_value); + }} + + string IConvertible.ToString(IFormatProvider? provider) + {{ + return ToString(""g"", provider); + }} + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + {{ + if (conversionType == typeof({_quantity.Name})) + return this; + else if (conversionType == typeof({_unitEnumName})) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return {_quantity.Name}.Info; + else if (conversionType == typeof(BaseDimensions)) + return {_quantity.Name}.BaseDimensions; + else + throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to {{conversionType}} is not supported.""); + }} + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + {{ + return Convert.ToUInt16(_value); + }} + + uint IConvertible.ToUInt32(IFormatProvider? provider) + {{ + return Convert.ToUInt32(_value); + }} + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + {{ + return Convert.ToUInt64(_value); + }} + + #endregion"); + } + + /// <inheritdoc cref="GetObsoleteAttributeOrNull(string)"/> + private static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); + + /// <inheritdoc cref="GetObsoleteAttributeOrNull(string)"/> + private static string? GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); + + /// <summary> + /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string + /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats + /// </summary> + private static string? GetObsoleteAttributeOrNull(string? obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) + ? null + : $"[Obsolete(\"{obsoleteText}\")]"; + } +} diff --git a/CodeGen/Generators/UnitsNetModularGen/SolutionGenerator.cs b/CodeGen/Generators/UnitsNetModularGen/SolutionGenerator.cs new file mode 100644 index 0000000000..7421cffb4c --- /dev/null +++ b/CodeGen/Generators/UnitsNetModularGen/SolutionGenerator.cs @@ -0,0 +1,69 @@ +using System; +using System.Text; +using CodeGen.Helpers; +using CodeGen.JsonTypes; + +namespace CodeGen.Generators.UnitsNetModularGen +{ + class SolutionGenerator:GeneratorBase + { + private readonly Quantity[] _quantities; + private readonly string _globalGuid = new Guid("660e8a78-57a3-4365-b7b5-336a552181ce").ToString("B").ToUpperInvariant(); // Randomly generated guids. + private readonly string _solutionGuid = new Guid("39648d62-4f58-4c39-9a1c-5a1d884dedab").ToString("B").ToUpperInvariant(); + + public SolutionGenerator(Quantity[] quantities) + { + _quantities = quantities; + } + + public string Generate() + { + StringBuilder sb = new(); + Writer.WL($@" +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29609.76 +MinimumVisualStudioVersion = 10.0.40219.1"); + + foreach (var quantity in _quantities) + { + var projectGuid = HashGuid.ToHashGuid(quantity.Name).ToString("B").ToUpperInvariant(); + Writer.WL($@" +Project(""{_globalGuid}"") = ""{quantity.Name}"", ""UnitsNet.Modular\GeneratedCode\{quantity.Name}\{quantity.Name}.csproj"", ""{projectGuid}"" +EndProject"); + sb.Append($"{projectGuid}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n"); + sb.Append($"{projectGuid}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n"); + sb.Append($"{projectGuid}.Debug|Any CPU.Deploy.0 = Debug|Any CPU\r\n"); + sb.Append($"{projectGuid}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n"); + sb.Append($"{projectGuid}.Release|Any CPU.Build.0 = Release|Any CPU\r\n"); + sb.Append($"{projectGuid}.Release|Any CPU.Deploy.0 = Release|Any CPU\r\n"); + } + + Writer.WL($@" +Project(""{_globalGuid}"") = ""UnitsNet.Core"", ""UnitsNet.Core\UnitsNet.Core.csproj"", ""{HashGuid.ToHashGuid("UnitsNet.Core").ToString("B").ToUpperInvariant()}"" +EndProject"); + + Writer.WL(@"Global + GlobalSection(ProjectConfigurationPlatforms) = postSolution + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution"); + + Writer.WL(sb.ToString()); + + Writer.WL($@" + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {_solutionGuid} + EndGlobalSection +EndGlobal +"); + return Writer.ToString(); + } + } +} diff --git a/CodeGen/Generators/UnitsNetModularGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetModularGen/UnitTypeGenerator.cs new file mode 100644 index 0000000000..e9b54529c3 --- /dev/null +++ b/CodeGen/Generators/UnitsNetModularGen/UnitTypeGenerator.cs @@ -0,0 +1,66 @@ +using CodeGen.Helpers; +using CodeGen.Helpers.UnitEnumValueAllocation; +using CodeGen.JsonTypes; + +namespace CodeGen.Generators.UnitsNetModularGen +{ + internal class UnitTypeGenerator : GeneratorBase + { + private readonly Quantity _quantity; + private readonly UnitEnumNameToValue _unitEnumNameToValue; + private readonly string _unitEnumName; + + public UnitTypeGenerator(Quantity quantity, UnitEnumNameToValue unitEnumNameToValue) + { + _quantity = quantity; + _unitEnumNameToValue = unitEnumNameToValue; + _unitEnumName = $"{quantity.Name}Unit"; + } + + public string Generate() + { + Writer.WL(GeneratedFileHeader); + Writer.WL($@" +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum {_unitEnumName} + {{"); + foreach (var unit in _quantity.Units) + { + if (unit.XmlDocSummary.HasText()) + { + Writer.WL(); + Writer.WL($@" + /// <summary> + /// {unit.XmlDocSummary} + /// </summary>"); + } + + if (unit.XmlDocRemarks.HasText()) + { + Writer.WL($@" + /// <remarks>{unit.XmlDocRemarks}</remarks>"); + } + + Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit.ObsoleteText)); + Writer.WL($@" + {unit.SingularName} = {_unitEnumNameToValue[unit.SingularName]},"); + } + + Writer.WL($@" + }} + + #pragma warning restore 1591 +}}"); + return Writer.ToString(); + } + + private static string? GetObsoleteAttributeOrNull(string? obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) + ? null + : $"[System.Obsolete(\"{obsoleteText}\")]"; + } +} diff --git a/CodeGen/Generators/UnitsNetModularGenerator.cs b/CodeGen/Generators/UnitsNetModularGenerator.cs new file mode 100644 index 0000000000..04026ac25e --- /dev/null +++ b/CodeGen/Generators/UnitsNetModularGenerator.cs @@ -0,0 +1,150 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System.IO; +using System.Linq; +using CodeGen.Generators.UnitsNetModularGen; +using CodeGen.Helpers.UnitEnumValueAllocation; +using CodeGen.JsonTypes; +using Serilog; + +namespace CodeGen.Generators +{ + /// <summary> + /// Code generator for UnitsNet and UnitsNet.Tests projects. + /// </summary> + internal static class UnitsNetModularGenerator + { + /// <summary> + /// Generate source code for UnitsNet project for the given parsed quantities. + /// Outputs files relative to the given root dir to these locations: + /// <list type="bullet"> + /// <item> + /// <description>UnitsNet/GeneratedCode (quantity and unit types, Quantity, UnitAbbreviationCache)</description> + /// </item> + /// <item> + /// <description>UnitsNet.Tests/GeneratedCode (tests)</description> + /// </item> + /// <item> + /// <description>UnitsNet.Tests/CustomCode (test stubs, one for each quantity if not already created)</description> + /// </item> + /// </list> + /// </summary> + /// <param name="rootDir">Path to repository root directory.</param> + /// <param name="quantities">The parsed quantities.</param> + /// <param name="quantityNameToUnitEnumValues">Allocated unit enum values for generating unit enum types.</param> + public static void Generate(string rootDir, Quantity[] quantities, QuantityNameToUnitEnumValues quantityNameToUnitEnumValues) + { + var outputDir = $"{rootDir}/UnitsNet.Modular/GeneratedCode"; + var testProjectDir = $"{rootDir}/UnitsNet.Modular.Tests"; + + // Ensure output directories exist + Directory.CreateDirectory($"{outputDir}/Quantities"); + Directory.CreateDirectory($"{outputDir}/Units"); + Directory.CreateDirectory($"{testProjectDir}/GeneratedCode"); + Directory.CreateDirectory($"{testProjectDir}/GeneratedCode/TestsBase"); + Directory.CreateDirectory($"{testProjectDir}/GeneratedCode/QuantityTests"); + + foreach (var quantity in quantities) + { + var projectPath = Path.Combine(outputDir, quantity.Name); + Directory.CreateDirectory(projectPath); + + UnitEnumNameToValue unitEnumValues = quantityNameToUnitEnumValues[quantity.Name]; + + GenerateQuantity(quantity, Path.Combine(projectPath, $"{quantity.Name}.g.cs")); + GenerateUnitType(quantity, Path.Combine(projectPath, $"{quantity.Name}Unit.g.cs"), unitEnumValues); + GenerateProject(quantity, Path.Combine(projectPath, $"{quantity.Name}.csproj")); + + // Example: CustomCode/Quantities/LengthTests inherits GeneratedCode/TestsBase/LengthTestsBase + // This way when new units are added to the quantity JSON definition, we auto-generate the new + // conversion function tests that needs to be manually implemented by the developer to fix the compile error + // so it cannot be forgotten. + // TODO modular + // GenerateQuantityTestBaseClass(quantity, $"{testProjectDir}/GeneratedCode/TestsBase/{quantity.Name}TestsBase.g.cs"); + // GenerateQuantityTestClassIfNotExists(quantity, $"{testProjectDir}/CustomCode/{quantity.Name}Tests.cs"); + + Log.Information("✅ {Quantity}", quantity.Name); + } + + Log.Information(""); + // TODO modular + // GenerateIQuantityTests(quantities, $"{testProjectDir}/GeneratedCode/IQuantityTests.g.cs"); + // GenerateStaticQuantity(quantities, $"{outputDir}/Quantity.g.cs"); + GenerateSolution(quantities, rootDir); + + var unitCount = quantities.SelectMany(q => q.Units).Count(); + Log.Information(""); + Log.Information("Total of {UnitCount} units and {QuantityCount} quantities", unitCount, quantities.Length); + Log.Information(""); + } + + private static void GenerateSolution(Quantity[] quantities, string outputDir) + { + var content = new SolutionGenerator(quantities).Generate(); + var filePath = Path.Combine(outputDir, "UnitsNet.Modular.sln"); + + File.WriteAllText(filePath, content); + Log.Information("✅ UnitsNet.Modular.sln"); + } + + // private static void GenerateQuantityTestClassIfNotExists(Quantity quantity, string filePath) + // { + // if (File.Exists(filePath)) return; + // + // var content = new UnitTestStubGenerator(quantity).Generate(); + // File.WriteAllText(filePath, content); + // Log.Information("✅ {Quantity} initial test stub", quantity.Name); + // } + + private static void GenerateQuantity(Quantity quantity, string filePath) + { + var content = new QuantityGenerator(quantity).Generate(); + File.WriteAllText(filePath, content); + } + + // private static void GenerateNumberToExtensions(Quantity quantity, string filePath) + // { + // var content = new NumberExtensionsGenerator(quantity).Generate(); + // File.WriteAllText(filePath, content); + // } + + // private static void GenerateNumberToExtensionsTestClass(Quantity quantity, string filePath) + // { + // var content = new NumberExtensionsTestClassGenerator(quantity).Generate(); + // File.WriteAllText(filePath, content); + // } + + private static void GenerateUnitType(Quantity quantity, string filePath, UnitEnumNameToValue unitEnumValues) + { + var content = new UnitTypeGenerator(quantity, unitEnumValues).Generate(); + File.WriteAllText(filePath, content); + } + + private static void GenerateProject(Quantity quantity, string filePath) + { + var content = new ProjectGenerator(quantity).Generate(); + File.WriteAllText(filePath, content); + } + + // private static void GenerateQuantityTestBaseClass(Quantity quantity, string filePath) + // { + // var content = new UnitTestBaseClassGenerator(quantity).Generate(); + // File.WriteAllText(filePath, content); + // } + // + // private static void GenerateIQuantityTests(Quantity[] quantities, string filePath) + // { + // var content = new IQuantityTestClassGenerator(quantities).Generate(); + // File.WriteAllText(filePath, content); + // Log.Information("✅ IQuantityTests.g.cs"); + // } + + // private static void GenerateStaticQuantity(Quantity[] quantities, string filePath) + // { + // var content = new StaticQuantityGenerator(quantities).Generate(); + // File.WriteAllText(filePath, content); + // Log.Information("✅ Quantity.g.cs"); + // } + } +} diff --git a/CodeGen/Program.cs b/CodeGen/Program.cs index d5589d5d1d..5d8d1dc0b4 100644 --- a/CodeGen/Program.cs +++ b/CodeGen/Program.cs @@ -70,6 +70,7 @@ public static int Main(bool verbose = false, DirectoryInfo? repositoryRoot = nul QuantityNameToUnitEnumValues quantityNameToUnitEnumValues = UnitEnumValueAllocator.AllocateNewUnitEnumValues($"{rootDir}/Common/UnitEnumValues.g.json", quantities); UnitsNetGenerator.Generate(rootDir, quantities, quantityNameToUnitEnumValues); + UnitsNetModularGenerator.Generate(rootDir, quantities, quantityNameToUnitEnumValues); if (updateNanoFrameworkDependencies) { diff --git a/README.md b/README.md index 3899257d92..3bf4e5ab6c 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,12 @@ [](https://codecov.io/gh/angularsen/UnitsNet) [](https://github.com/vshymanskyy/StandWithUkraine/blob/main/docs/README.md) +## Feature branch agl/split-nuget-v5 + +### Challenges +- UnitSystem and BaseUnits depending on 7 projects for SI units, change to string? Move to SI project and extension methods? +- + ## Units.NET Add strongly typed quantities to your code and get merrily on with your life. diff --git a/UnitsNet.Core.Tests/Class1.cs b/UnitsNet.Core.Tests/Class1.cs new file mode 100644 index 0000000000..89c18369a7 --- /dev/null +++ b/UnitsNet.Core.Tests/Class1.cs @@ -0,0 +1,13 @@ +using FluentAssertions; +using Xunit; + +namespace UnitsNet.Core.Tests; + +public class Class1 +{ + [Fact] + public void Foo() + { + Quantity.Infos.Should().ContainSingle().Which.Name.Should().Be("HowMuch"); + } +} diff --git a/UnitsNet.Core.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Core.Tests/CustomQuantities/HowMuch.cs new file mode 100644 index 0000000000..f842c1d0c2 --- /dev/null +++ b/UnitsNet.Core.Tests/CustomQuantities/HowMuch.cs @@ -0,0 +1,62 @@ +namespace UnitsNet.Core.Tests.CustomQuantities +{ + /// <inheritdoc cref="IQuantity"/> + /// <summary> + /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. + /// </summary> + public readonly struct HowMuch : IQuantity + { + public HowMuch(double value, HowMuchUnit unit) + { + Unit = unit; + Value = value; + } + + Enum IQuantity.Unit => Unit; + public HowMuchUnit Unit { get; } + + public QuantityValue Value { get; } + + #region IQuantity + + private static readonly HowMuch Zero = new HowMuch(0, HowMuchUnit.Some); + + public BaseDimensions Dimensions => BaseDimensions.Dimensionless; + + public static QuantityInfo Info => new( + nameof(HowMuch), + typeof(HowMuchUnit), + new UnitInfo[] + { + new UnitInfo<HowMuchUnit>(HowMuchUnit.Some, "Some", new[] { "sm", "some" }, BaseUnits.Undefined), + new UnitInfo<HowMuchUnit>(HowMuchUnit.ATon, "Tons", new[] { "tns", "tons" }, BaseUnits.Undefined), + new UnitInfo<HowMuchUnit>(HowMuchUnit.AShitTon, "ShitTons", new[] { "st", "shitn" }, BaseUnits.Undefined), + }, + HowMuchUnit.Some, + Zero, + BaseDimensions.Dimensionless, + From); + + public QuantityInfo QuantityInfo => Info; + + public static IQuantity From(QuantityValue value, Enum unit) => new HowMuch((double)value, (HowMuchUnit)unit); + + public double As(Enum unit) => Convert.ToDouble(unit); + + // public double As(UnitSystem unitSystem) => throw new NotImplementedException(); + + public IQuantity ToUnit(Enum unit) + { + if (unit is HowMuchUnit howMuchUnit) return new HowMuch(As(unit), howMuchUnit); + throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit)); + } + + // public IQuantity ToUnit(UnitSystem unitSystem) => throw new NotImplementedException(); + + public override string ToString() => $"{Value} {Unit}"; + public string ToString(string? format, IFormatProvider? formatProvider) => $"HowMuch ({format}, {formatProvider})"; + public string ToString(IFormatProvider? provider) => $"HowMuch ({provider})"; + + #endregion + } +} diff --git a/UnitsNet.Core.Tests/CustomQuantities/HowMuchUnit.cs b/UnitsNet.Core.Tests/CustomQuantities/HowMuchUnit.cs new file mode 100644 index 0000000000..06eca78649 --- /dev/null +++ b/UnitsNet.Core.Tests/CustomQuantities/HowMuchUnit.cs @@ -0,0 +1,12 @@ +namespace UnitsNet.Core.Tests.CustomQuantities +{ + /// <summary> + /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. + /// </summary> + public enum HowMuchUnit + { + Some, + ATon, + AShitTon + } +} diff --git a/UnitsNet.Core.Tests/UnitsNet.Core.Tests.csproj b/UnitsNet.Core.Tests/UnitsNet.Core.Tests.csproj new file mode 100644 index 0000000000..249b811e8e --- /dev/null +++ b/UnitsNet.Core.Tests/UnitsNet.Core.Tests.csproj @@ -0,0 +1,24 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net7.0</TargetFramework> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="FluentAssertions" Version="6.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" /> + <PackageReference Include="xunit" Version="2.4.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> + <PrivateAssets>all</PrivateAssets> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + </PackageReference> + <DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Core/AmbiguousUnitParseException.cs b/UnitsNet.Core/AmbiguousUnitParseException.cs new file mode 100644 index 0000000000..822c3c783d --- /dev/null +++ b/UnitsNet.Core/AmbiguousUnitParseException.cs @@ -0,0 +1,28 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +namespace UnitsNet +{ + /// <summary> + /// Unable to parse because more than one unit of the given quantity type had this exact unit abbreviation. + /// Example: Length.Parse("1 pt") will throw <see cref="AmbiguousUnitParseException" />, because both + /// <see cref="LengthUnit.DtpPoint" /> and + /// <see cref="LengthUnit.PrinterPoint" /> have "pt" as their abbreviation. + /// </summary> + public class AmbiguousUnitParseException : UnitsNetException + { + /// <inheritdoc /> + public AmbiguousUnitParseException(string message) : base(message) + { + HResult = 2; + } + + /// <inheritdoc /> + public AmbiguousUnitParseException(string message, Exception innerException) : base(message, innerException) + { + HResult = 2; + } + } +} diff --git a/UnitsNet.Core/AssemblyInfo.cs b/UnitsNet.Core/AssemblyInfo.cs new file mode 100644 index 0000000000..d897374117 --- /dev/null +++ b/UnitsNet.Core/AssemblyInfo.cs @@ -0,0 +1,9 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(true)] +[assembly: InternalsVisibleTo("UnitsNet.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] + diff --git a/UnitsNet.Core/BaseDimensions.cs b/UnitsNet.Core/BaseDimensions.cs new file mode 100644 index 0000000000..593625fd2e --- /dev/null +++ b/UnitsNet.Core/BaseDimensions.cs @@ -0,0 +1,236 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Text; +using System.Linq; + +namespace UnitsNet +{ + /// <summary> + /// Represents the base dimensions of a quantity. + /// </summary> + public sealed class BaseDimensions + { + /// <summary>Creates an instance of <see cref="BaseDimensions"/>.</summary> + public BaseDimensions(int length, int mass, int time, int current, int temperature, int amount, int luminousIntensity) + { + Length = length; + Mass = mass; + Time = time; + Current = current; + Temperature = temperature; + Amount = amount; + LuminousIntensity = luminousIntensity; + } + + /// <summary> + /// Checks if the dimensions represent a base quantity. + /// </summary> + /// <returns>True if the dimensions represent a base quantity, otherwise false.</returns> + public bool IsBaseQuantity() + { + var dimensionsArray = new[] { Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity }; + bool onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1; + return onlyOneEqualsOne; + } + + /// <summary> + /// Checks if the dimensions represent a derived quantity. + /// </summary> + /// <returns>True if the dimensions represent a derived quantity, otherwise false.</returns> + public bool IsDerivedQuantity() + { + return !IsBaseQuantity() && !IsDimensionless(); + } + + /// <summary> + /// Checks if this base dimensions object represents a dimensionless quantity. + /// </summary> + /// <returns>True if this object represents a dimensionless quantity, otherwise false.</returns> + public bool IsDimensionless() + { + return this == Dimensionless; + } + + /// <inheritdoc /> + public override bool Equals(object? obj) + { + if (obj is not BaseDimensions other) + return false; + + return Length == other.Length && + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; + } + + /// <inheritdoc /> + public override int GetHashCode() + { + return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); + } + + /// <summary> + /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension. + /// </summary> + /// <param name="right">Other dimensions.</param> + /// <returns>Resulting dimensions.</returns> + public BaseDimensions Multiply(BaseDimensions right) + { + if(right is null) + throw new ArgumentNullException(nameof(right)); + + return new BaseDimensions( + Length + right.Length, + Mass + right.Mass, + Time + right.Time, + Current + right.Current, + Temperature + right.Temperature, + Amount + right.Amount, + LuminousIntensity + right.LuminousIntensity); + } + + /// <summary> + /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension. + /// </summary> + /// <param name="right">Other dimensions.</param> + /// <returns>Resulting dimensions.</returns> + public BaseDimensions Divide(BaseDimensions right) + { + if(right is null) + throw new ArgumentNullException(nameof(right)); + + return new BaseDimensions( + Length - right.Length, + Mass - right.Mass, + Time - right.Time, + Current - right.Current, + Temperature - right.Temperature, + Amount - right.Amount, + LuminousIntensity - right.LuminousIntensity); + } + + /// <summary> + /// Check if two dimensions are equal. + /// </summary> + /// <param name="left">Left.</param> + /// <param name="right">Right.</param> + /// <returns>True if equal.</returns> + public static bool operator ==(BaseDimensions? left, BaseDimensions? right) + { + return left?.Equals(right!) ?? right is null; + } + + /// <summary> + /// Check if two dimensions are unequal. + /// </summary> + /// <param name="left">Left.</param> + /// <param name="right">Right.</param> + /// <returns>True if not equal.</returns> + public static bool operator !=(BaseDimensions? left, BaseDimensions? right) + { + return !(left == right); + } + + /// <summary> + /// Multiply two dimensions. + /// </summary> + /// <param name="left">Left.</param> + /// <param name="right">Right.</param> + /// <returns>Resulting dimensions.</returns> + public static BaseDimensions operator *(BaseDimensions left, BaseDimensions right) + { + if (left is null) throw new ArgumentNullException(nameof(left)); + if (right is null) throw new ArgumentNullException(nameof(right)); + + return left.Multiply(right); + } + + /// <summary> + /// Divide two dimensions. + /// </summary> + /// <param name="left">Left.</param> + /// <param name="right">Right.</param> + /// <returns>Resulting dimensions.</returns> + public static BaseDimensions operator /(BaseDimensions left, BaseDimensions right) + { + if (left is null) throw new ArgumentNullException(nameof(left)); + if (right is null) throw new ArgumentNullException(nameof(right)); + + return left.Divide(right); + } + + /// <inheritdoc /> + public override string ToString() + { + var sb = new StringBuilder(); + + AppendDimensionString(sb, "Length", Length); + AppendDimensionString(sb, "Mass", Mass); + AppendDimensionString(sb, "Time", Time); + AppendDimensionString(sb, "Current", Current); + AppendDimensionString(sb, "Temperature", Temperature); + AppendDimensionString(sb, "Amount", Amount); + AppendDimensionString(sb, "LuminousIntensity", LuminousIntensity); + + return sb.ToString(); + } + + private static void AppendDimensionString(StringBuilder sb, string name, int value) + { + var absoluteValue = Math.Abs(value); + + if(absoluteValue > 0) + { + sb.AppendFormat("[{0}]", name); + + if(absoluteValue > 1) + sb.AppendFormat("^{0}", value); + } + } + + /// <summary> + /// Gets the length dimensions (L). + /// </summary> + public int Length { get; } + + /// <summary> + /// Gets the mass dimensions (M). + /// </summary> + public int Mass{ get; } + + /// <summary> + /// Gets the time dimensions (T). + /// </summary> + public int Time{ get; } + + /// <summary> + /// Gets the electric current dimensions (I). + /// </summary> + public int Current{ get; } + + /// <summary> + /// Gets the temperature dimensions (Θ). + /// </summary> + public int Temperature{ get; } + + /// <summary> + /// Gets the amount of substance dimensions (N). + /// </summary> + public int Amount{ get; } + + /// <summary> + /// Gets the luminous intensity dimensions (J). + /// </summary> + public int LuminousIntensity{ get; } + + /// <summary> + /// Represents a dimensionless (unitless) quantity. + /// </summary> + public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); + } +} diff --git a/UnitsNet.Core/BaseUnits.cs b/UnitsNet.Core/BaseUnits.cs new file mode 100644 index 0000000000..529d43660e --- /dev/null +++ b/UnitsNet.Core/BaseUnits.cs @@ -0,0 +1,206 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Text; + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Represents the base units for a quantity. All quantities, both base and derived, can be + /// represented by a combination of these seven base units. + /// </summary> + public sealed class BaseUnits : IEquatable<BaseUnits> + { + /// <summary> + /// Represents BaseUnits that have not been defined. + /// </summary> + public static BaseUnits Undefined { get; } = new BaseUnits(); + + /// <summary> + /// Creates an instance of if the base units class that represents the base units for a quantity. + /// All quantities, both base and derived, can be represented by a combination of these seven base units. + /// </summary> + /// <param name="length">The length unit (L).</param> + /// <param name="mass">The mass unit (M).</param> + /// <param name="time">The time unit (T).</param> + /// <param name="current">The electric current unit (I).</param> + /// <param name="temperature">The temperature unit (Θ).</param> + /// <param name="amount">The amount of substance unit (N).</param> + /// <param name="luminousIntensity">The luminous intensity unit (J).</param> + public BaseUnits( + Enum? length = null, + Enum? mass = null, + Enum? time = null, + Enum? current = null, + Enum? temperature = null, + Enum? amount = null, + Enum? luminousIntensity = null) + { + Length = length; + Mass = mass; + Time = time; + Current = current; + Temperature = temperature; + Amount = amount; + LuminousIntensity = luminousIntensity; + + IsFullyDefined = Length is not null && + Mass is not null & + Time is not null && + Current is not null && + Temperature is not null && + Amount is not null && + LuminousIntensity is not null; + } + + /// <inheritdoc /> + public override bool Equals(object? obj) + { + return obj is BaseUnits other && Equals(other); + } + + /// <summary> + /// Checks if all of the base units are equal to another instance's. + /// </summary> + /// <param name="other">The other instance to check if equal to.</param> + /// <returns>True if equal, otherwise false.</returns> + public bool Equals(BaseUnits? other) + { + if (other is null) + return false; + + return Length == other.Length && + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; + } + + /// <summary> + /// Checks if the base units are a subset of another. Undefined base units are ignored. + /// If all base united are undefined (equal to <see cref="BaseUnits.Undefined"/>), + /// IsSubsetOf will return true only if other is also equal to <see cref="BaseUnits.Undefined"/>. + /// </summary> + /// <param name="other">The other <see cref="BaseUnits"/> to compare to.</param> + /// <returns>True if the base units are a subset of other, otherwise false.</returns> + public bool IsSubsetOf(BaseUnits other) + { + if (other == null) throw new ArgumentNullException(nameof(other)); + + // If all base units are undefined, can only be a subset of another where all base units are undefined. + if (Equals(Undefined)) + return other.Equals(Undefined); + + return (Length == null || Length == other.Length) && + (Mass == null || Mass == other.Mass) && + (Time == null || Time == other.Time) && + (Current == null || Current == other.Current) && + (Temperature == null || Temperature == other.Temperature) && + (Amount == null || Amount == other.Amount) && + (LuminousIntensity == null || LuminousIntensity == other.LuminousIntensity); + } + + /// <inheritdoc /> + public override int GetHashCode() + { + return new + { + Length, + Mass, + Time, + Current, + Temperature, + Amount, + LuminousIntensity + }.GetHashCode(); + } + + /// <summary> + /// Checks if this instance is equal to another. + /// </summary> + /// <param name="left">The left instance.</param> + /// <param name="right">The right instance.</param> + /// <returns>True if equal, otherwise false.</returns> + /// <seealso cref="Equals(BaseUnits)"/> + public static bool operator ==(BaseUnits? left, BaseUnits? right) + { + return left?.Equals(right!) ?? right is null; + } + + /// <summary> + /// Checks if this instance is not equal to another. + /// </summary> + /// <param name="left">The left instance.</param> + /// <param name="right">The right instance.</param> + /// <returns>True if not equal, otherwise false.</returns> + /// <seealso cref="Equals(BaseUnits)"/> + public static bool operator !=(BaseUnits? left, BaseUnits? right) + { + return !(left == right); + } + + /// <inheritdoc /> + public override string ToString() + { + var sb = new StringBuilder(); + + string GetDefaultAbbreviation(Enum? unitOrNull) => unitOrNull is { } unit + ? UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit) + : "N/A"; + + sb.AppendFormat("[Length]: {0}, ", GetDefaultAbbreviation(Length)); + sb.AppendFormat("[Mass]: {0}, ", GetDefaultAbbreviation(Mass)); + sb.AppendFormat("[Time]: {0}, ", GetDefaultAbbreviation(Time)); + sb.AppendFormat("[Current]: {0}, ", GetDefaultAbbreviation(Current)); + sb.AppendFormat("[Temperature]: {0}, ", GetDefaultAbbreviation(Temperature)); + sb.AppendFormat("[Amount]: {0}, ", GetDefaultAbbreviation(Amount)); + sb.AppendFormat("[LuminousIntensity]: {0}", GetDefaultAbbreviation(LuminousIntensity)); + + return sb.ToString(); + } + + /// <summary> + /// Gets the length unit (L). + /// </summary> + public Enum? Length { get; } + + /// <summary> + /// Gets the mass unit (M). + /// </summary> + public Enum? Mass { get; } + + /// <summary> + /// Gets the time unit (T). + /// </summary> + public Enum? Time { get; } + + /// <summary> + /// Gets the electric current unit (I). + /// </summary> + public Enum? Current { get; } + + /// <summary> + /// Gets the temperature unit (Θ). + /// </summary> + public Enum? Temperature { get; } + + /// <summary> + /// Gets the amount of substance unit (N). + /// </summary> + public Enum? Amount { get; } + + /// <summary> + /// Gets the luminous intensity unit (J). + /// </summary> + public Enum? LuminousIntensity { get; } + + /// <summary> + /// Gets whether or not all of the base units are defined. + /// </summary> + public bool IsFullyDefined { get; } + } +} diff --git a/UnitsNet.Core/Comparison.cs b/UnitsNet.Core/Comparison.cs new file mode 100644 index 0000000000..ac6726c3e2 --- /dev/null +++ b/UnitsNet.Core/Comparison.cs @@ -0,0 +1,237 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +namespace UnitsNet +{ + /// <summary> + /// Helper methods to perform relative and absolute comparison. + /// </summary> + public static class Comparison + { + /// <summary> + /// <para> + /// Checks if two values are equal with a given relative or absolute tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// <paramref name="referenceValue" /> and + /// <paramref name="otherValue" /> as a percentage of <paramref name="referenceValue" />. A relative tolerance of + /// 0.01 means the + /// absolute difference of <paramref name="referenceValue" /> and <paramref name="otherValue" /> must be within +/- + /// 1%. + /// <example> + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// <code> + /// Equals(a, b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between + /// <paramref name="referenceValue" /> and + /// <paramref name="otherValue" /> as a fixed number. + /// <example> + /// In this example, the two values will be equal if abs(<paramref name="referenceValue" /> - + /// <paramref name="otherValue" />) <= 0.01 + /// <code> + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// </summary> + /// <param name="referenceValue"> + /// The reference value. If using relative tolerance, it is the value which the relative + /// tolerance will be calculated against. + /// </param> + /// <param name="otherValue">The value to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">Whether the tolerance is absolute or relative.</param> + /// <returns></returns> + public static bool Equals(double referenceValue, double otherValue, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + switch (comparisonType) + { + case ComparisonType.Relative: + return EqualsRelative(referenceValue, otherValue, tolerance); + case ComparisonType.Absolute: + return EqualsAbsolute(referenceValue, otherValue, tolerance); + default: + throw new InvalidOperationException("The given ComparisonType is not supported."); + } + } + + /// <summary> + /// <para> + /// Checks if two values are equal with a given relative or absolute tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// <paramref name="referenceValue" /> and + /// <paramref name="otherValue" /> as a percentage of <paramref name="referenceValue" />. A relative tolerance of + /// 0.01 means the + /// absolute difference of <paramref name="referenceValue" /> and <paramref name="otherValue" /> must be within +/- + /// 1%. + /// <example> + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// <code> + /// Equals(a, b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between + /// <paramref name="referenceValue" /> and + /// <paramref name="otherValue" /> as a fixed number. + /// <example> + /// In this example, the two values will be equal if abs(<paramref name="referenceValue" /> - + /// <paramref name="otherValue" />) <= 0.01 + /// <code> + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// </summary> + /// <param name="referenceValue"> + /// The reference value. If using relative tolerance, it is the value which the relative + /// tolerance will be calculated against. + /// </param> + /// <param name="otherValue">The value to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">Whether the tolerance is absolute or relative.</param> + /// <returns></returns> + public static bool Equals(decimal referenceValue, decimal otherValue, decimal tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + switch (comparisonType) + { + case ComparisonType.Relative: + return EqualsRelative(referenceValue, otherValue, tolerance); + case ComparisonType.Absolute: + return EqualsAbsolute(referenceValue, otherValue, tolerance); + default: + throw new InvalidOperationException("The given ComparisonType is not supported."); + } + } + + /// <summary> + /// Checks if two values are equal with a given relative tolerance. + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// <paramref name="referenceValue" /> and + /// <paramref name="otherValue" /> as a percentage of <paramref name="referenceValue" />. A relative tolerance of + /// 0.01 means the + /// absolute difference of <paramref name="referenceValue" /> and <paramref name="otherValue" /> must be within +/- + /// 1%. + /// <example> + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// <code> + /// EqualsRelative(a, b, 0.01); + /// </code> + /// </example> + /// </para> + /// </summary> + /// <param name="referenceValue">The reference value which the tolerance will be calculated against.</param> + /// <param name="otherValue">The value to compare to.</param> + /// <param name="tolerance">The relative tolerance. Must be greater than or equal to 0.</param> + /// <returns>True if the two values are equal within the given relative tolerance, otherwise false.</returns> + public static bool EqualsRelative(double referenceValue, double otherValue, double tolerance) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + var maxVariation = Math.Abs(referenceValue * tolerance); + return Math.Abs(referenceValue - otherValue) <= maxVariation; + } + + /// <summary> + /// Checks if two values are equal with a given relative tolerance. + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between + /// <paramref name="referenceValue" /> and + /// <paramref name="otherValue" /> as a percentage of <paramref name="referenceValue" />. A relative tolerance of + /// 0.01 means the + /// absolute difference of <paramref name="referenceValue" /> and <paramref name="otherValue" /> must be within +/- + /// 1%. + /// <example> + /// In this example, the two values will be equal if the value of b is within +/- 1% of a. + /// <code> + /// EqualsRelative(a, b, 0.01); + /// </code> + /// </example> + /// </para> + /// </summary> + /// <param name="referenceValue">The reference value which the tolerance will be calculated against.</param> + /// <param name="otherValue">The value to compare to.</param> + /// <param name="tolerance">The relative tolerance. Must be greater than or equal to 0.</param> + /// <returns>True if the two values are equal within the given relative tolerance, otherwise false.</returns> + public static bool EqualsRelative(decimal referenceValue, decimal otherValue, decimal tolerance) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + var maxVariation = Math.Abs(referenceValue * tolerance); + return Math.Abs(referenceValue - otherValue) <= maxVariation; + } + + /// <summary> + /// Checks if two values are equal with a given absolute tolerance. + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between <paramref name="value1" /> + /// and + /// <paramref name="value2" /> as a fixed number. + /// <example> + /// In this example, the two values will be equal if abs(<paramref name="value1" /> - + /// <paramref name="value2" />) <= 0.01 + /// <code> + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// </summary> + /// <param name="value1">The first value.</param> + /// <param name="value2">The second value.</param> + /// <param name="tolerance">The absolute tolerance. Must be greater than or equal to 0.</param> + /// <returns>True if the two values are equal within the given absolute tolerance, otherwise false.</returns> + public static bool EqualsAbsolute(double value1, double value2, double tolerance) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + return Math.Abs(value1 - value2) <= tolerance; + } + + /// <summary> + /// Checks if two values are equal with a given absolute tolerance. + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between <paramref name="value1" /> + /// and + /// <paramref name="value2" /> as a fixed number. + /// <example> + /// In this example, the two values will be equal if abs(<paramref name="value1" /> - + /// <paramref name="value2" />) <= 0.01 + /// <code> + /// Equals(a, b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// </summary> + /// <param name="value1">The first value.</param> + /// <param name="value2">The second value.</param> + /// <param name="tolerance">The absolute tolerance. Must be greater than or equal to 0.</param> + /// <returns>True if the two values are equal within the given absolute tolerance, otherwise false.</returns> + public static bool EqualsAbsolute(decimal value1, decimal value2, decimal tolerance) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + + return Math.Abs(value1 - value2) <= tolerance; + } + } +} diff --git a/UnitsNet.Core/ComparisonType.cs b/UnitsNet.Core/ComparisonType.cs new file mode 100644 index 0000000000..18f76cfdd3 --- /dev/null +++ b/UnitsNet.Core/ComparisonType.cs @@ -0,0 +1,21 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +namespace UnitsNet +{ + /// <summary> + /// Specifies if the comparison between numbers is absolute or relative. + /// </summary> + public enum ComparisonType + { + /// <summary> + /// Error margin in relative size to a reference value. + /// </summary> + Relative, + + /// <summary> + /// Error margin as absolute size. + /// </summary> + Absolute + } +} diff --git a/UnitsNet.Core/CompiledLambdas.cs b/UnitsNet.Core/CompiledLambdas.cs new file mode 100644 index 0000000000..56790cadaa --- /dev/null +++ b/UnitsNet.Core/CompiledLambdas.cs @@ -0,0 +1,312 @@ +using System; +using System.Linq.Expressions; + +namespace UnitsNet +{ + /// <summary> + /// Compiled lambda expressions that can be invoked with generic run-time parameters. This is used for performance as + /// it is far faster than reflection based alternatives. + /// </summary> + internal static class CompiledLambdas + { + /// <summary> + /// Multiplies the given values. + /// </summary> + /// <typeparam name="T">The type of the operation (left hand side, right hand side, and result).</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The multiplied result.</returns> + internal static T Multiply<T>(T left, T right) => MultiplyImplementation<T, T, T>.Invoke(left, right); + + /// <summary> + /// Multiplies the given values. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <typeparam name="TResult">The result type.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The multiplied result.</returns> + internal static TResult Multiply<TLeft, TRight, TResult>(TLeft left, TRight right) => + MultiplyImplementation<TLeft, TRight, TResult>.Invoke(left, right); + + /// <summary> + /// Divides the given values. + /// </summary> + /// <typeparam name="T">The type of the operation (left hand side, right hand side, and result).</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The divided result.</returns> + internal static T Divide<T>(T left, T right) => DivideImplementation<T, T, T>.Invoke(left, right); + + /// <summary> + /// Divides the given values. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <typeparam name="TResult">The result type.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The divided result.</returns> + internal static TResult Divide<TLeft, TRight, TResult>(TLeft left, TRight right) => + DivideImplementation<TLeft, TRight, TResult>.Invoke(left, right); + + /// <summary> + /// Adds the given values. + /// </summary> + /// <typeparam name="T">The type of the operation (left hand side, right hand side, and result).</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The added result.</returns> + internal static T Add<T>(T left, T right) => AddImplementation<T, T, T>.Invoke(left, right); + + /// <summary> + /// Adds the given values. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <typeparam name="TResult">The result type.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The added result.</returns> + internal static TResult Add<TLeft, TRight, TResult>(TLeft left, TRight right) => + AddImplementation<TLeft, TRight, TResult>.Invoke(left, right); + + /// <summary> + /// Subtracts the given values. + /// </summary> + /// <typeparam name="T">The type of the operation (left hand side, right hand side, and result).</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The subtracted result.</returns> + internal static T Subtract<T>(T left, T right) => SubtractImplementation<T, T, T>.Invoke(left, right); + + /// <summary> + /// Subtracts the given values. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <typeparam name="TResult">The result type.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The subtracted result.</returns> + internal static TResult Subtract<TLeft, TRight, TResult>(TLeft left, TRight right) => + SubtractImplementation<TLeft, TRight, TResult>.Invoke(left, right); + + /// <summary> + /// Gets the modulus of the given values. + /// </summary> + /// <typeparam name="T">The type of the operation (left hand side, right hand side, and result).</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The modulus.</returns> + internal static T Modulo<T>(T left, T right) => ModuloImplementation<T, T, T>.Invoke(left, right); + + /// <summary> + /// Gets the modulus of the given values. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <typeparam name="TResult">The result type.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>The modulus.</returns> + internal static TResult Modulo<TLeft, TRight, TResult>(TLeft left, TRight right) => + ModuloImplementation<TLeft, TRight, TResult>.Invoke(left, right); + + /// <summary> + /// Checks if the left and right hand side are equal. + /// </summary> + /// <typeparam name="T">The type of both the left and right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if equal, otherwise false.</returns> + internal static bool Equal<T>(T left, T right) => EqualImplementation<T, T>.Invoke(left, right); + + /// <summary> + /// Checks if the left and right hand side are equal. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if equal, otherwise false.</returns> + internal static bool Equal<TLeft, TRight>(TLeft left, TRight right) => + EqualImplementation<TLeft, TRight>.Invoke(left, right); + + /// <summary> + /// Checks if the left and right hand side are not equal. + /// </summary> + /// <typeparam name="T">The type of both the left and right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if not equal, otherwise false.</returns> + internal static bool NotEqual<T>(T left, T right) => NotEqualImplementation<T, T>.Invoke(left, right); + + /// <summary> + /// Checks if the left and right hand side are not equal. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if not equal, otherwise false.</returns> + internal static bool NotEqual<TLeft, TRight>(TLeft left, TRight right) => + NotEqualImplementation<TLeft, TRight>.Invoke(left, right); + + /// <summary> + /// Checks if the left hand side is less than the right hand side. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if the left hand side is less than the right hand side, otherwise false.</returns> + internal static bool LessThan<TLeft, TRight>(TLeft left, TRight right) => + LessThanImplementation<TLeft, TRight>.Invoke(left, right); + + /// <summary> + /// Checks if the left hand side is less than or equal to the right hand side. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if the left hand side is less than or equal to the right hand side, otherwise false.</returns> + internal static bool LessThanOrEqual<TLeft, TRight>(TLeft left, TRight right) => + LessThanOrEqualImplementation<TLeft, TRight>.Invoke(left, right); + + /// <summary> + /// Checks if the left hand side is greater than the right hand side. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if the left hand side is greater than the right hand side, otherwise false.</returns> + internal static bool GreaterThan<TLeft, TRight>(TLeft left, TRight right) => + GreaterThanImplementation<TLeft, TRight>.Invoke(left, right); + + /// <summary> + /// Checks if the left hand side is greater than or equal to the right hand side. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side.</typeparam> + /// <typeparam name="TRight">The type of the right hand side.</typeparam> + /// <param name="left">The left hand side parameter.</param> + /// <param name="right">The right hand side parameter.</param> + /// <returns>True if the left hand side is greater than or equal to the right hand side, otherwise false.</returns> + internal static bool GreaterThanOrEqual<TLeft, TRight>(TLeft left, TRight right) => + GreaterThanOrEqualImplementation<TLeft, TRight>.Invoke(left, right); + + #region Implementation Classes + + private static class MultiplyImplementation<TLeft, TRight, TResult> + { + private readonly static Func<TLeft, TRight, TResult> Function = + CreateBinaryFunction<TLeft, TRight, TResult>(Expression.Multiply); + + internal static TResult Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class DivideImplementation<TLeft, TRight, TResult> + { + private readonly static Func<TLeft, TRight, TResult> Function = + CreateBinaryFunction<TLeft, TRight, TResult>(Expression.Divide); + + internal static TResult Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class AddImplementation<TLeft, TRight, TResult> + { + private readonly static Func<TLeft, TRight, TResult> Function = + CreateBinaryFunction<TLeft, TRight, TResult>(Expression.Add); + + internal static TResult Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class SubtractImplementation<TLeft, TRight, TResult> + { + private readonly static Func<TLeft, TRight, TResult> Function = + CreateBinaryFunction<TLeft, TRight, TResult>(Expression.Subtract); + + internal static TResult Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class ModuloImplementation<TLeft, TRight, TResult> + { + private readonly static Func<TLeft, TRight, TResult> Function = + CreateBinaryFunction<TLeft, TRight, TResult>(Expression.Modulo); + + internal static TResult Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class EqualImplementation<TLeft, TRight> + { + private readonly static Func<TLeft, TRight, bool> Function = + CreateBinaryFunction<TLeft, TRight, bool>(Expression.Equal); + + internal static bool Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class NotEqualImplementation<TLeft, TRight> + { + private readonly static Func<TLeft, TRight, bool> Function = + CreateBinaryFunction<TLeft, TRight, bool>(Expression.NotEqual); + + internal static bool Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class LessThanImplementation<TLeft, TRight> + { + private readonly static Func<TLeft, TRight, bool> Function = + CreateBinaryFunction<TLeft, TRight, bool>(Expression.LessThan); + + internal static bool Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class LessThanOrEqualImplementation<TLeft, TRight> + { + private readonly static Func<TLeft, TRight, bool> Function = + CreateBinaryFunction<TLeft, TRight, bool>(Expression.LessThanOrEqual); + + internal static bool Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class GreaterThanImplementation<TLeft, TRight> + { + private readonly static Func<TLeft, TRight, bool> Function = + CreateBinaryFunction<TLeft, TRight, bool>(Expression.GreaterThan); + + internal static bool Invoke(TLeft left, TRight right) => Function(left, right); + } + + private static class GreaterThanOrEqualImplementation<TLeft, TRight> + { + private readonly static Func<TLeft, TRight, bool> Function = + CreateBinaryFunction<TLeft, TRight, bool>(Expression.GreaterThanOrEqual); + + internal static bool Invoke(TLeft left, TRight right) => Function(left, right); + } + + #endregion + + /// <summary> + /// Creates a compiled lambda for the given <see cref="Func{Expression, Expression, BinaryExpression}"/>. + /// </summary> + /// <typeparam name="TLeft">The type of the left hand side of the binary operation.</typeparam> + /// <typeparam name="TRight">The type of the right hand side of the binary operation.</typeparam> + /// <typeparam name="TResult">The type of the result of the binary operation.</typeparam> + /// <param name="expressionCreationFunction">The function that creates a binary expression to compile.</param> + /// <returns>The compiled binary expression.</returns> + private static Func<TLeft, TRight, TResult> CreateBinaryFunction<TLeft, TRight, TResult>(Func<Expression, Expression, BinaryExpression> expressionCreationFunction) + { + var leftParameter = Expression.Parameter(typeof(TLeft), "left"); + var rightParameter = Expression.Parameter(typeof(TRight), "right"); + + var binaryExpression = expressionCreationFunction(leftParameter, rightParameter); + var lambda = Expression.Lambda<Func<TLeft, TRight, TResult>>(binaryExpression, leftParameter, rightParameter); + + return lambda.Compile(); + } + } +} diff --git a/UnitsNet.Core/CustomCode/Quantity.cs b/UnitsNet.Core/CustomCode/Quantity.cs new file mode 100644 index 0000000000..14f119e1ed --- /dev/null +++ b/UnitsNet.Core/CustomCode/Quantity.cs @@ -0,0 +1,177 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; + +namespace UnitsNet +{ + public partial class Quantity + { + private static readonly Lazy<Dictionary<(Type, string), UnitInfo>> UnitTypeAndNameToUnitInfoLazy; + + static Quantity() + { + // Automatically load quantity types from UnitsNet libraries. Custom quantity types must be explicitly loaded. + // Example full name: "UnitsNet, Version=5.0.0.0, Culture=neutral, PublicKeyToken=f8601875a1f041da" + // Example full name: "UnitsNet.Modular.Length, Version=5.0.0.0, Culture=neutral, PublicKeyToken=f8601875a1f041da" + var unitsNetAssemblyRegex = new Regex(@"^UnitsNet(\.[^,]+)?\,"); + var quantityTypes = AppDomain.CurrentDomain.GetAssemblies() + .Where(ass => ass.FullName != null && unitsNetAssemblyRegex.IsMatch(ass.FullName)) + .SelectMany(ass => ass.DefinedTypes.Where(t => typeof(IQuantity).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)) + .ToList(); + + QuantityTypes = quantityTypes.AsReadOnly(); + + List<QuantityInfo> quantityInfos = quantityTypes + .Select(t => t.GetProperty("Info", BindingFlags.Public|BindingFlags.Static)?.GetMethod?.Invoke(null, null) as QuantityInfo) + .Where(info => info != null) + .Select(info => info!) + .ToList(); + + Names = quantityInfos.Select(qt => qt.Name).ToArray(); + EnumToQuantityInfo = new ReadOnlyDictionary<Type, QuantityInfo>(quantityInfos.ToDictionary(qt => qt.UnitType, qt => qt)); + + Infos = quantityInfos + .OrderBy(quantityInfo => quantityInfo.Name) + .ToArray(); + + UnitTypeAndNameToUnitInfoLazy = new Lazy<Dictionary<(Type, string), UnitInfo>>(() => + { + return Infos + .SelectMany(quantityInfo => quantityInfo.UnitInfos + .Select(unitInfo => new KeyValuePair<(Type, string), UnitInfo>( + (unitInfo.Value.GetType(), unitInfo.Name), + unitInfo))) + .ToDictionary(x => x.Key, x => x.Value); + }); + } + + /// <summary> + /// Map unit enum type to its corresponding QuantityInfo, such as LengthUnit -> Length.Info. + /// </summary> + public static ReadOnlyDictionary<Type,QuantityInfo> EnumToQuantityInfo { get; } + + /// <summary> + /// All quantity types found in loaded assemblies that implement <see cref="IQuantity"/>. + /// </summary> + public static ReadOnlyCollection<TypeInfo> QuantityTypes { get; } + + /// <summary> + /// All enum value names of <see cref="Infos"/>, such as "Length" and "Mass". + /// </summary> + public static string[] Names { get; } + + /// <summary> + /// All quantity information objects, such as <see cref="Length.Info"/> and <see cref="Mass.Info"/>. + /// </summary> + public static IReadOnlyList<QuantityInfo> Infos { get; } + + /// <summary> + /// Get <see cref="UnitInfo"/> for a given unit enum value. + /// </summary> + public static UnitInfo GetUnitInfo(Enum unitEnum) => UnitTypeAndNameToUnitInfoLazy.Value[(unitEnum.GetType(), unitEnum.ToString())]; + + /// <summary> + /// Try to get <see cref="UnitInfo"/> for a given unit enum value. + /// </summary> + public static bool TryGetUnitInfo(Enum unitEnum, [NotNullWhen(true)] out UnitInfo? unitInfo) => + UnitTypeAndNameToUnitInfoLazy.Value.TryGetValue((unitEnum.GetType(), unitEnum.ToString()), out unitInfo); + + /// <summary> + /// Dynamically construct a quantity. + /// </summary> + /// <param name="value">Numeric value.</param> + /// <param name="unit">Unit enum value.</param> + /// <returns>An <see cref="IQuantity"/> object.</returns> + /// <exception cref="ArgumentException">Unit value is not a know unit enum type.</exception> + public static IQuantity From(QuantityValue value, Enum unit) + { + if (!EnumToQuantityInfo.TryGetValue(unit.GetType(), out QuantityInfo? quantityInfo)) + { + throw new ArgumentException($"Unit enum type '{unit.GetType()}' is not a known unit enum type. Make sure to expose a static QuantityInfo getter-property named 'Info' on the quantity class and to configure this unit enum type there.", nameof(unit)); + } + + return quantityInfo.CreateQuantity(value, unit); + } + + /// <inheritdoc cref="TryFrom(QuantityValue,System.Enum,out UnitsNet.IQuantity)"/> + public static bool TryFrom(double value, Enum unit, [NotNullWhen(true)] out IQuantity? quantity) + { + // Implicit cast to QuantityValue would prevent TryFrom from being called, + // so we need to explicitly check this here for double arguments. + if (double.IsNaN(value) || double.IsInfinity(value)) + { + quantity = default(IQuantity); + return false; + } + + return TryFrom((QuantityValue)value, unit, out quantity); + } + + /// <inheritdoc cref="TryFrom(QuantityValue,System.Enum,out UnitsNet.IQuantity)"/> + public static bool TryFrom(QuantityValue value, Enum unit, [NotNullWhen(true)] out IQuantity? quantity) + { + if (!EnumToQuantityInfo.TryGetValue(unit.GetType(), out QuantityInfo? quantityInfo)) + { + quantity = null; + return false; + } + + quantity = quantityInfo.CreateQuantity(value, unit); + return true; + } + + /// <inheritdoc cref="Parse(IFormatProvider, System.Type,string)"/> + public static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); + + /// <summary> + /// Dynamically parse a quantity string representation. + /// </summary> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="quantityType">Type of quantity, such as <see cref="Length"/>.</param> + /// <param name="quantityString">Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type.</param> + /// <returns>The parsed quantity.</returns> + /// <exception cref="ArgumentException">Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type.</exception> + public static IQuantity Parse(IFormatProvider? formatProvider, Type quantityType, string quantityString) + { + if (!typeof(IQuantity).IsAssignableFrom(quantityType)) + throw new ArgumentException($"Type {quantityType} must be of type UnitsNet.IQuantity."); + + if (TryParse(formatProvider, quantityType, quantityString, out IQuantity? quantity)) return quantity; + + throw new ArgumentException($"Quantity string could not be parsed to quantity {quantityType}."); + } + + private static bool TryParse(IFormatProvider? formatProvider, Type quantityType, string quantityString, [NotNullWhen(true)] out IQuantity? quantity) + { + quantity = null; + + if (!typeof(IQuantity).IsAssignableFrom(quantityType)) return false; + + // TODO Create dictionary to optimize lookup. + if (Infos.FirstOrDefault(i => i.ValueType == quantityType) is not { } qi) return false; + + return qi.TryParse(formatProvider, quantityString, out quantity); + } + + /// <inheritdoc cref="TryParse(IFormatProvider,System.Type,string,out UnitsNet.IQuantity)"/> + public static bool TryParse(Type quantityType, string quantityString, [NotNullWhen(true)] out IQuantity? quantity) => + TryParse(null, quantityType, quantityString, out quantity); + + /// <summary> + /// Get a list of quantities that has the given base dimensions. + /// </summary> + /// <param name="baseDimensions">The base dimensions to match.</param> + public static IEnumerable<QuantityInfo> GetQuantitiesWithBaseDimensions(BaseDimensions baseDimensions) + { + return Infos.Where(info => info.BaseDimensions.Equals(baseDimensions)); + } + } +} diff --git a/UnitsNet.Core/CustomCode/QuantityParser.cs b/UnitsNet.Core/CustomCode/QuantityParser.cs new file mode 100644 index 0000000000..23a0b16881 --- /dev/null +++ b/UnitsNet.Core/CustomCode/QuantityParser.cs @@ -0,0 +1,257 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; + +// ReSharper disable once CheckNamespace +namespace UnitsNet +{ + internal delegate TQuantity QuantityFromDelegate<out TQuantity, in TUnitType>(QuantityValue value, TUnitType fromUnit) + where TQuantity : IQuantity + where TUnitType : Enum; + + internal class QuantityParser + { + /// <summary> + /// Allow integer, floating point or exponential number formats. + /// </summary> + private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent; + + private readonly UnitAbbreviationsCache _unitAbbreviationsCache; + private readonly UnitParser _unitParser; + + public static QuantityParser Default { get; } + + public QuantityParser(UnitAbbreviationsCache? unitAbbreviationsCache) + { + _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; + _unitParser = new UnitParser(_unitAbbreviationsCache); + } + + static QuantityParser() + { + Default = new QuantityParser(UnitAbbreviationsCache.Default); + } + + [SuppressMessage("ReSharper", "UseStringInterpolation")] + internal TQuantity Parse<TQuantity, TUnitType>(string str, + IFormatProvider? formatProvider, + QuantityFromDelegate<TQuantity, TUnitType> fromDelegate) + where TQuantity : IQuantity + where TUnitType : Enum + { + if (str == null) throw new ArgumentNullException(nameof(str)); + str = str.Trim(); + + var regex = CreateRegexForQuantity<TUnitType>(formatProvider); + + if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString)) + { + var ex = new FormatException("Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional."); + ex.Data["input"] = str; + throw ex; + } + + return ParseWithRegex(valueString, unitString, fromDelegate, formatProvider); + } + + [SuppressMessage("ReSharper", "UseStringInterpolation")] + internal bool TryParse(string? str, + IFormatProvider? formatProvider, + Type unitType, + IEnumerable<string> unitAbbreviations, + QuantityFactory quantityFactory, + out IQuantity? result) + { + result = default; + + if (string.IsNullOrWhiteSpace(str)) return false; + str = str!.Trim(); // netstandard2.0 nullable quirk + + Regex regex = CreateRegexForUnitAbbreviations(unitAbbreviations); + + return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) && + TryParseWithRegex(valueString, unitString, unitType, quantityFactory, formatProvider, out result); + } + + [SuppressMessage("ReSharper", "UseStringInterpolation")] + internal bool TryParse<TQuantity, TUnitType>(string? str, + IFormatProvider? formatProvider, + QuantityFromDelegate<TQuantity, TUnitType> fromDelegate, + out TQuantity result) + where TQuantity : struct, IQuantity + where TUnitType : struct, Enum + { + result = default; + + if (string.IsNullOrWhiteSpace(str)) return false; + str = str!.Trim(); // netstandard2.0 nullable quirk + + var regex = CreateRegexForQuantity<TUnitType>(formatProvider); + + return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) && + TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); + } + + /// <summary> + /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are compatible. + /// </summary> + [SuppressMessage("ReSharper", "UseStringInterpolation")] + internal bool TryParse<TQuantity, TUnitType>(string str, + IFormatProvider? formatProvider, + QuantityFromDelegate<TQuantity, TUnitType> fromDelegate, + out IQuantity? result) + where TQuantity : struct, IQuantity + where TUnitType : struct, Enum + { + if (TryParse(str, formatProvider, fromDelegate, out TQuantity parsedQuantity)) + { + result = parsedQuantity; + return true; + } + + result = default; + return false; + } + + internal string CreateRegexPatternForUnit<TUnitType>( + TUnitType unit, + IFormatProvider? formatProvider, + bool matchEntireString = true) + where TUnitType : Enum + { + var unitAbbreviations = _unitAbbreviationsCache.GetUnitAbbreviations(unit, formatProvider); + return GetRegexPatternForUnitAbbreviations(unitAbbreviations, matchEntireString); + } + + private static string GetRegexPatternForUnitAbbreviations(IEnumerable<string> unitAbbreviations, bool matchEntireString) + { + var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); + return matchEntireString ? $"^{pattern}$" : pattern; + } + + private static string GetRegexPatternForUnitAbbreviations(IEnumerable<string> abbreviations) + { + var orderedAbbreviations = abbreviations + .OrderByDescending(s => s.Length) // Important to order by length -- if "m" is before "mm" and the input is "mm", it will match just "m" + .Select(Regex.Escape) // Escape special regex characters + .ToArray(); + + var abbreviationsPiped = $"{string.Join("|", orderedAbbreviations)}"; + return $@"(?<value>.*?)\s?(?<unit>{abbreviationsPiped})"; + } + + /// <summary> + /// Parse a string given a particular regular expression. + /// </summary> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + private TQuantity ParseWithRegex<TQuantity, TUnitType>(string valueString, + string unitString, + QuantityFromDelegate<TQuantity, TUnitType> fromDelegate, + IFormatProvider? formatProvider) + where TQuantity : IQuantity + where TUnitType : Enum + { + var value = double.Parse(valueString, ParseNumberStyles, formatProvider); + var parsedUnit = _unitParser.Parse<TUnitType>(unitString, formatProvider); + return fromDelegate(value, parsedUnit); + } + + /// <summary> + /// Parse a string given a particular regular expression. + /// </summary> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + private bool TryParseWithRegex<TQuantity, TUnitType>(string? valueString, + string? unitString, + QuantityFromDelegate<TQuantity, TUnitType> fromDelegate, + IFormatProvider? formatProvider, + out TQuantity result) + where TQuantity : struct, IQuantity + where TUnitType : struct, Enum + { + result = default; + + if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) + return false; + + if (!_unitParser.TryParse<TUnitType>(unitString, formatProvider, out var parsedUnit)) + return false; + + result = fromDelegate(value, parsedUnit); + return true; + } + + /// <summary> + /// Parse a string given a particular regular expression. + /// </summary> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + private bool TryParseWithRegex(string? valueString, + string? unitString, + Type unitType, + QuantityFactory quantityFactory, + IFormatProvider? formatProvider, + out IQuantity? result) + { + result = default; + + if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) return false; + if (!_unitParser.TryParse(unitString, unitType, formatProvider, out var parsedUnit)) return false; + + result = quantityFactory(value, parsedUnit); + return true; + } + + private static bool TryExtractValueAndUnit(Regex regex, string str, [NotNullWhen(true)] out string? valueString, [NotNullWhen(true)] out string? unitString) + { + var match = regex.Match(str); + + // the regex coming in contains all allowed units as strings. + // That means if the unit in str is not formatted right + // the regex.Match will ether put str or string.empty into Groups[0] and Groups[1] + // Therefore a mismatch can be detected by comparing the values of this two groups. + if (match.Groups[0].Value == match.Groups[1].Value) + { + str = UnitParser.NormalizeUnitString(str); + match = regex.Match(str); + } + + var groups = match.Groups; + + var valueGroup = groups["value"]; + var unitGroup = groups["unit"]; + if (!valueGroup.Success || !unitGroup.Success) + { + valueString = null; + unitString = null; + return false; + } + + valueString = valueGroup.Value; + unitString = unitGroup.Value; + return true; + } + + private string CreateRegexPatternForQuantity<TUnitType>(IFormatProvider? formatProvider) where TUnitType : Enum + { + IReadOnlyList<string> unitAbbreviations = _unitAbbreviationsCache.GetAllUnitAbbreviationsForQuantity(typeof(TUnitType), formatProvider); + return GetRegexPatternForUnitAbbreviations(unitAbbreviations, matchEntireString: true); + } + + private Regex CreateRegexForQuantity<TUnitType>(IFormatProvider? formatProvider) where TUnitType : Enum + { + var pattern = CreateRegexPatternForQuantity<TUnitType>(formatProvider); + return new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); + } + + private static Regex CreateRegexForUnitAbbreviations(IEnumerable<string> unitAbbreviations) + { + var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); + return new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); + } + } +} diff --git a/UnitsNet.Core/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet.Core/CustomCode/UnitAbbreviationsCache.cs new file mode 100644 index 0000000000..925f364bae --- /dev/null +++ b/UnitsNet.Core/CustomCode/UnitAbbreviationsCache.cs @@ -0,0 +1,310 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; + +using UnitTypeToLookup = System.Collections.Generic.Dictionary<System.Type, UnitsNet.UnitValueAbbreviationLookup>; + +// ReSharper disable once CheckNamespace +namespace UnitsNet +{ + /// <summary> + /// Cache of the mapping between unit enum values and unit abbreviation strings for one or more cultures. + /// A static instance <see cref="Default"/> is used internally for ToString() and Parse() of quantities and units. + /// </summary> + public sealed class UnitAbbreviationsCache + { + private readonly Dictionary<IFormatProvider, UnitTypeToLookup> _lookupsForCulture; + + /// <summary> + /// Fallback culture used by <see cref="GetUnitAbbreviations{TUnitType}" /> and <see cref="GetDefaultAbbreviation{TUnitType}" /> + /// if no abbreviations are found with a given culture. + /// </summary> + /// <example> + /// User wants to call <see cref="UnitParser.Parse{TUnitType}" /> or <see cref="Length.ToString()" /> with Russian + /// culture, but no translation is defined, so we return the US English definition as a last resort. If it's not + /// defined there either, an exception is thrown. + /// </example> + internal static readonly CultureInfo FallbackCulture = new("en-US"); + + /// <summary> + /// The static instance used internally for ToString() and Parse() of quantities and units. + /// </summary> + public static UnitAbbreviationsCache Default { get; } + + /// <summary> + /// Create an instance of the cache and load all the abbreviations defined in the library. + /// </summary> + public UnitAbbreviationsCache() + { + _lookupsForCulture = new Dictionary<IFormatProvider, UnitTypeToLookup>(); + + LoadGeneratedAbbreviations(); + } + + static UnitAbbreviationsCache() + { + Default = new UnitAbbreviationsCache(); + } + + private void LoadGeneratedAbbreviations() + { + foreach (TypeInfo quantityType in Quantity.QuantityTypes) + { + // TODO Cache reflection. + var mapGeneratedLocalizationsMethod = quantityType.GetMethod("MapGeneratedLocalizations", BindingFlags.NonPublic | BindingFlags.Static); + mapGeneratedLocalizationsMethod?.Invoke(null, new object[]{this}); + } + } + + /// <summary> + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as <see cref="UnitsNet.Units.LengthUnit"/> or to extend with third-party unit enums + /// in order to <see cref="UnitParser.Parse{TUnitType}"/> or <see cref="GetDefaultAbbreviation{TUnitType}"/> on them later. + /// </summary> + /// <param name="unit">The unit enum value.</param> + /// <param name="abbreviations">Unit abbreviations to add.</param> + /// <typeparam name="TUnitType">The type of unit enum.</typeparam> + public void MapUnitToAbbreviation<TUnitType>(TUnitType unit, params string[] abbreviations) where TUnitType : Enum + { + PerformAbbreviationMapping(unit, CultureInfo.CurrentCulture, false, true, abbreviations); + } + + /// <summary> + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as <see cref="UnitsNet.Units.LengthUnit"/> or to extend with third-party unit enums + /// in order to <see cref="UnitParser.Parse{TUnitType}"/> or <see cref="GetDefaultAbbreviation{TUnitType}"/> on them later. + /// </summary> + /// <param name="unit">The unit enum value.</param> + /// <param name="abbreviation">Unit abbreviations to add as default.</param> + /// <typeparam name="TUnitType">The type of unit enum.</typeparam> + public void MapUnitToDefaultAbbreviation<TUnitType>(TUnitType unit, string abbreviation) where TUnitType : Enum + { + PerformAbbreviationMapping(unit, CultureInfo.CurrentCulture, true, true, abbreviation); + } + + /// <summary> + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as <see cref="LengthUnit"/> or to extend with third-party unit enums + /// in order to <see cref="UnitParser.Parse{TUnitType}"/> or <see cref="GetDefaultAbbreviation{TUnitType}"/> on them later. + /// </summary> + /// <param name="unit">The unit enum value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="abbreviations">Unit abbreviations to add.</param> + /// <typeparam name="TUnitType">The type of unit enum.</typeparam> + public void MapUnitToAbbreviation<TUnitType>(TUnitType unit, IFormatProvider? formatProvider, params string[] abbreviations) where TUnitType : Enum + { + PerformAbbreviationMapping(unit, formatProvider, false, true, abbreviations); + } + + /// <summary> + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as <see cref="LengthUnit"/> or to extend with third-party unit enums + /// in order to <see cref="UnitParser.Parse{TUnitType}"/> or <see cref="GetDefaultAbbreviation{TUnitType}"/> on them later. + /// </summary> + /// <param name="unit">The unit enum value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="abbreviation">Unit abbreviation to add as default.</param> + /// <typeparam name="TUnitType">The type of unit enum.</typeparam> + public void MapUnitToDefaultAbbreviation<TUnitType>(TUnitType unit, IFormatProvider? formatProvider, string abbreviation) where TUnitType : Enum + { + PerformAbbreviationMapping(unit, formatProvider, true, true, abbreviation); + } + + /// <summary> + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as <see cref="LengthUnit"/> or to extend with third-party unit enums + /// in order to <see cref="UnitParser.Parse{TUnitType}"/> or <see cref="GetDefaultAbbreviation{TUnitType}"/> on them later. + /// </summary> + /// <param name="unitType">The unit enum type.</param> + /// <param name="unitValue">The unit enum value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="abbreviations">Unit abbreviations to add.</param> + public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider, params string[] abbreviations) + { + var enumValue = (Enum)Enum.ToObject(unitType, unitValue); + PerformAbbreviationMapping(enumValue, formatProvider, false, true, abbreviations); + } + + /// <summary> + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as <see cref="LengthUnit"/> or to extend with third-party unit enums + /// in order to <see cref="UnitParser.Parse{TUnitType}"/> or <see cref="GetDefaultAbbreviation{TUnitType}"/> on them later. + /// </summary> + /// <param name="unitType">The unit enum type.</param> + /// <param name="unitValue">The unit enum value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="abbreviation">Unit abbreviation to add as default.</param> + public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider, string abbreviation) + { + var enumValue = (Enum)Enum.ToObject(unitType, unitValue); + PerformAbbreviationMapping(enumValue, formatProvider, true, true, abbreviation); + } + + internal void PerformAbbreviationMapping(Enum unitValue, IFormatProvider? formatProvider, bool setAsDefault, bool allowAbbreviationLookup, params string[] abbreviations) + { + if (abbreviations == null) + throw new ArgumentNullException(nameof(abbreviations)); + + formatProvider ??= CultureInfo.CurrentCulture; + + if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) + quantitiesForProvider = _lookupsForCulture[formatProvider] = new UnitTypeToLookup(); + + var unitType = unitValue.GetType(); + if (!quantitiesForProvider.TryGetValue(unitType, out var unitToAbbreviations)) + unitToAbbreviations = quantitiesForProvider[unitType] = new UnitValueAbbreviationLookup(); + + var unitValueAsInt = Convert.ToInt32(unitValue); + foreach (var abbr in abbreviations) + { + unitToAbbreviations.Add(unitValueAsInt, abbr, setAsDefault, allowAbbreviationLookup); + } + } + + /// <summary> + /// Gets the default abbreviation for a given unit. If a unit has more than one abbreviation defined, then it returns the first one. + /// Example: GetDefaultAbbreviation<LengthUnit>(LengthUnit.Kilometer) => "km" + /// </summary> + /// <param name="unit">The unit enum value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <typeparam name="TUnitType">The type of unit enum.</typeparam> + /// <returns>The default unit abbreviation string.</returns> + public string GetDefaultAbbreviation<TUnitType>(TUnitType unit, IFormatProvider? formatProvider = null) where TUnitType : Enum + { + var unitType = typeof(TUnitType); + + if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + { + return !Equals(formatProvider, FallbackCulture) + ? GetDefaultAbbreviation(unit, FallbackCulture) + : throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + } + + var abbreviations = lookup!.GetAbbreviationsForUnit(unit); + if (abbreviations.Count == 0) + { + return !Equals(formatProvider, FallbackCulture) + ? GetDefaultAbbreviation(unit, FallbackCulture) + : throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + } + + return abbreviations.First(); + } + + /// <summary> + /// Gets the default abbreviation for a given unit type and its numeric enum value. + /// If a unit has more than one abbreviation defined, then it returns the first one. + /// Example: GetDefaultAbbreviation<LengthUnit>(typeof(LengthUnit), 1) => "cm" + /// </summary> + /// <param name="unitType">The unit enum type.</param> + /// <param name="unitValue">The unit enum value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The default unit abbreviation string.</returns> + public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider = null) + { + if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + { + return !Equals(formatProvider, FallbackCulture) + ? GetDefaultAbbreviation(unitType, unitValue, FallbackCulture) + : throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); + } + + var abbreviations = lookup!.GetAbbreviationsForUnit(unitValue); + if (abbreviations.Count == 0) + { + return !Equals(formatProvider, FallbackCulture) + ? GetDefaultAbbreviation(unitType, unitValue, FallbackCulture) + : throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); + } + + return abbreviations.First(); + } + + /// <summary> + /// Get all abbreviations for unit. + /// </summary> + /// <typeparam name="TUnitType">Enum type for units.</typeparam> + /// <param name="unit">Enum value for unit.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>Unit abbreviations associated with unit.</returns> + public string[] GetUnitAbbreviations<TUnitType>(TUnitType unit, IFormatProvider? formatProvider = null) where TUnitType : Enum + { + return GetUnitAbbreviations(typeof(TUnitType), Convert.ToInt32(unit), formatProvider); + } + + /// <summary> + /// Get all abbreviations for unit. + /// </summary> + /// <param name="unitType">Enum type for unit.</param> + /// <param name="unitValue">Enum value for unit.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>Unit abbreviations associated with unit.</returns> + public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider? formatProvider = null) + { + formatProvider ??= CultureInfo.CurrentCulture; + + if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + { + return !Equals(formatProvider, FallbackCulture) + ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) + : new string[] { }; + } + + var abbreviations = lookup!.GetAbbreviationsForUnit(unitValue); + if (abbreviations.Count == 0) + { + return !Equals(formatProvider, FallbackCulture) + ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) + : new string[] { }; + } + + return abbreviations.ToArray(); + } + + /// <summary> + /// Get all abbreviations for all units of a quantity. + /// </summary> + /// <param name="unitEnumType">Enum type for unit.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>Unit abbreviations associated with unit.</returns> + public IReadOnlyList<string> GetAllUnitAbbreviationsForQuantity(Type unitEnumType, IFormatProvider? formatProvider = null) + { + formatProvider ??= CultureInfo.CurrentCulture; + + if (!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) + { + return !Equals(formatProvider, FallbackCulture) + ? GetAllUnitAbbreviationsForQuantity(unitEnumType, FallbackCulture) + : new string[] { }; + } + + return lookup!.GetAllUnitAbbreviationsForQuantity(); + } + + internal bool TryGetUnitValueAbbreviationLookup(Type unitType, IFormatProvider? formatProvider, out UnitValueAbbreviationLookup? unitToAbbreviations) + { + unitToAbbreviations = null; + + formatProvider ??= CultureInfo.CurrentCulture; + + if (!_lookupsForCulture.TryGetValue(formatProvider, out UnitTypeToLookup? quantitiesForProvider)) + { + return !Equals(formatProvider, FallbackCulture) && + TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations); + } + + if (!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) + { + return !Equals(formatProvider, FallbackCulture) && + TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations); + } + + return true; + } + } +} diff --git a/UnitsNet.Core/CustomCode/UnitParser.cs b/UnitsNet.Core/CustomCode/UnitParser.cs new file mode 100644 index 0000000000..4762800779 --- /dev/null +++ b/UnitsNet.Core/CustomCode/UnitParser.cs @@ -0,0 +1,221 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; + +// ReSharper disable once CheckNamespace +namespace UnitsNet +{ + /// <summary> + /// Parses units given a unit abbreviations cache. + /// The static instance <see cref="Default"/> is used internally to parse quantities and units using the + /// default abbreviations cache for all units and abbreviations defined in the library. + /// </summary> + public sealed class UnitParser + { + private readonly UnitAbbreviationsCache _unitAbbreviationsCache; + + /// <summary> + /// The default static instance used internally to parse quantities and units using the + /// default abbreviations cache for all units and abbreviations defined in the library. + /// </summary> + public static UnitParser Default { get; } + + /// <summary> + /// Create a parser using the given unit abbreviations cache. + /// </summary> + /// <param name="unitAbbreviationsCache"></param> + public UnitParser(UnitAbbreviationsCache? unitAbbreviationsCache) + { + _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; + } + + static UnitParser() + { + Default = new UnitParser(UnitAbbreviationsCache.Default); + } + + /// <summary> + /// Parses a unit abbreviation for a given unit enumeration type. + /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer + /// </summary> + /// <param name="unitAbbreviation"></param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <typeparam name="TUnitType"></typeparam> + /// <returns></returns> + public TUnitType Parse<TUnitType>(string unitAbbreviation, IFormatProvider? formatProvider = null) where TUnitType : Enum + { + return (TUnitType)Parse(unitAbbreviation, typeof(TUnitType), formatProvider); + } + + /// <summary> + /// Parse a unit abbreviation, such as "kg" or "m", to the unit enum value of the enum type + /// <paramref name="unitType" />. + /// </summary> + /// <param name="unitAbbreviation"> + /// Unit abbreviation, such as "kg" or "m" for <see cref="MassUnit.Kilogram" /> and + /// <see cref="LengthUnit.Meter" /> respectively. + /// </param> + /// <param name="unitType">Unit enum type, such as <see cref="MassUnit" /> and <see cref="LengthUnit" />.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>Unit enum value, such as <see cref="MassUnit.Kilogram" />.</returns> + /// <exception cref="UnitNotFoundException">No units match the abbreviation.</exception> + /// <exception cref="AmbiguousUnitParseException">More than one unit matches the abbreviation.</exception> + public Enum Parse(string? unitAbbreviation, Type unitType, IFormatProvider? formatProvider = null) + { + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + unitAbbreviation = unitAbbreviation.Trim(); + + if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + throw new UnitNotFoundException($"No abbreviations defined for unit type [{unitType}] for culture [{formatProvider}]."); + + var unitIntValues = abbreviations!.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + + if (unitIntValues.Count == 0) + { + unitAbbreviation = NormalizeUnitString(unitAbbreviation); + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + } + + // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished + if (unitIntValues.Count > 1) + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); + + switch (unitIntValues.Count) + { + case 1: + return (Enum) Enum.ToObject(unitType, unitIntValues[0]); + case 0: + // Retry with fallback culture, if different. + if (!Equals(formatProvider, UnitAbbreviationsCache.FallbackCulture)) + { + return Parse(unitAbbreviation, unitType, UnitAbbreviationsCache.FallbackCulture); + } + + throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}] for unit type [{unitType}]."); + default: + string unitsCsv = string.Join(", ", unitIntValues.Select(x => Enum.GetName(unitType, x)).ToArray()); + throw new AmbiguousUnitParseException( + $"Cannot parse \"{unitAbbreviation}\" since it could be either of these: {unitsCsv}"); + } + } + + internal static string NormalizeUnitString(string unitAbbreviation) + { + // remove all whitespace in the string + unitAbbreviation = new string(unitAbbreviation.Where(c => !char.IsWhiteSpace(c)).ToArray()); + + unitAbbreviation = unitAbbreviation.Replace("^-9", "⁻⁹"); + unitAbbreviation = unitAbbreviation.Replace("^-8", "⁻⁸"); + unitAbbreviation = unitAbbreviation.Replace("^-7", "⁻⁷"); + unitAbbreviation = unitAbbreviation.Replace("^-6", "⁻⁶"); + unitAbbreviation = unitAbbreviation.Replace("^-5", "⁻⁵"); + unitAbbreviation = unitAbbreviation.Replace("^-4", "⁻⁴"); + unitAbbreviation = unitAbbreviation.Replace("^-3", "⁻³"); + unitAbbreviation = unitAbbreviation.Replace("^-2", "⁻²"); + unitAbbreviation = unitAbbreviation.Replace("^-1", "⁻¹"); + unitAbbreviation = unitAbbreviation.Replace("^1", ""); + unitAbbreviation = unitAbbreviation.Replace("^2", "²"); + unitAbbreviation = unitAbbreviation.Replace("^3", "³"); + unitAbbreviation = unitAbbreviation.Replace("^4", "⁴"); + unitAbbreviation = unitAbbreviation.Replace("^5", "⁵"); + unitAbbreviation = unitAbbreviation.Replace("^6", "⁶"); + unitAbbreviation = unitAbbreviation.Replace("^7", "⁷"); + unitAbbreviation = unitAbbreviation.Replace("^8", "⁸"); + unitAbbreviation = unitAbbreviation.Replace("^9", "⁹"); + unitAbbreviation = unitAbbreviation.Replace("*", "·"); + // "\u03bc" = Lower case Greek letter 'Mu' + // "\u00b5" = Micro sign + unitAbbreviation = unitAbbreviation.Replace("\u03bc", "\u00b5"); + + return unitAbbreviation; + } + + /// <summary> + /// Try to parse a unit abbreviation. + /// </summary> + /// <param name="unitAbbreviation">The string value.</param> + /// <param name="unit">The unit enum value as out result.</param> + /// <typeparam name="TUnitType">Type of unit enum.</typeparam> + /// <returns>True if successful.</returns> + public bool TryParse<TUnitType>(string unitAbbreviation, out TUnitType unit) where TUnitType : struct, Enum + { + return TryParse(unitAbbreviation, null, out unit); + } + + /// <summary> + /// Try to parse a unit abbreviation. + /// </summary> + /// <param name="unitAbbreviation">The string value.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="unit">The unit enum value as out result.</param> + /// <typeparam name="TUnitType">Type of unit enum.</typeparam> + /// <returns>True if successful.</returns> + public bool TryParse<TUnitType>(string? unitAbbreviation, IFormatProvider? formatProvider, out TUnitType unit) where TUnitType : struct, Enum + { + unit = default; + + if (!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) + return false; + + unit = (TUnitType)unitObj; + return true; + } + + /// <summary> + /// Try to parse a unit abbreviation. + /// </summary> + /// <param name="unitAbbreviation">The string value.</param> + /// <param name="unitType">Type of unit enum.</param> + /// <param name="unit">The unit enum value as out result.</param> + /// <returns>True if successful.</returns> + public bool TryParse(string unitAbbreviation, Type unitType, [NotNullWhen(true)] out Enum? unit) + { + return TryParse(unitAbbreviation, unitType, null, out unit); + } + + /// <summary> + /// Try to parse a unit abbreviation. + /// </summary> + /// <param name="unitAbbreviation">The string value.</param> + /// <param name="unitType">Type of unit enum.</param> + /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <param name="unit">The unit enum value as out result.</param> + /// <returns>True if successful.</returns> + public bool TryParse(string? unitAbbreviation, Type unitType, IFormatProvider? formatProvider, [NotNullWhen(true)] out Enum? unit) + { + if (unitAbbreviation == null) + { + unit = default; + return false; + } + + unitAbbreviation = unitAbbreviation.Trim(); + unit = default; + + if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + return false; + + var unitIntValues = abbreviations!.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + + if (unitIntValues.Count == 0) + { + unitAbbreviation = NormalizeUnitString(unitAbbreviation); + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + } + + // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished + if (unitIntValues.Count > 1) + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); + + if (unitIntValues.Count != 1) + return false; + + unit = (Enum)Enum.ToObject(unitType, unitIntValues[0]); + return true; + } + } +} diff --git a/UnitsNet.Core/CustomCode/UnitValueAbbreviationLookup.cs b/UnitsNet.Core/CustomCode/UnitValueAbbreviationLookup.cs new file mode 100644 index 0000000000..d303658682 --- /dev/null +++ b/UnitsNet.Core/CustomCode/UnitValueAbbreviationLookup.cs @@ -0,0 +1,94 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +namespace UnitsNet +{ + internal class UnitToAbbreviationMap : ConcurrentDictionary<int, IReadOnlyList<string>> { } + internal class AbbreviationToUnitMap : ConcurrentDictionary<string, IReadOnlyList<int>> { } + + internal class UnitValueAbbreviationLookup + { + private readonly UnitToAbbreviationMap _unitToAbbreviationMap = new(); + private readonly AbbreviationToUnitMap _abbreviationToUnitMap = new(); + private readonly AbbreviationToUnitMap _lowerCaseAbbreviationToUnitMap = new(); + private Lazy<string[]> _allUnitAbbreviationsLazy; + private readonly object _syncRoot = new(); + + public UnitValueAbbreviationLookup() + { + _allUnitAbbreviationsLazy = new Lazy<string[]>(ComputeAllUnitAbbreviationsValue); + } + + internal IReadOnlyList<string> GetAllUnitAbbreviationsForQuantity() + { + return _allUnitAbbreviationsLazy.Value; + } + + internal IReadOnlyList<string> GetAbbreviationsForUnit<TUnitType>(TUnitType unit) where TUnitType : Enum + { + return GetAbbreviationsForUnit(Convert.ToInt32(unit)); + } + + internal IReadOnlyList<string> GetAbbreviationsForUnit(int unit) + { + if (!_unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) + return new List<string>(0); + + return abbreviations.ToList(); + } + + internal IReadOnlyList<int> GetUnitsForAbbreviation(string abbreviation, bool ignoreCase) + { + var lowerCaseAbbreviation = abbreviation.ToLower(); + var key = ignoreCase ? lowerCaseAbbreviation : abbreviation; + var map = ignoreCase ? _lowerCaseAbbreviationToUnitMap : _abbreviationToUnitMap; + + if (!map.TryGetValue(key, out IReadOnlyList<int>? units)) + return new List<int>(0); + + return units.ToList(); + } + + internal void Add(int unit, string abbreviation, bool setAsDefault = false, bool allowAbbreviationLookup = true) + { + // Restrict concurrency on writes. + // By using ConcurrencyDictionary and immutable IReadOnlyList instances, we don't need to lock on reads. + lock (_syncRoot) + { + var lowerCaseAbbreviation = abbreviation.ToLower(); + + if (allowAbbreviationLookup) + { + _abbreviationToUnitMap.AddOrUpdate(abbreviation, + addValueFactory: _ => new List<int> { unit }, + updateValueFactory: (_, existing) => existing.Append(unit).Distinct().ToList()); + + _lowerCaseAbbreviationToUnitMap.AddOrUpdate(lowerCaseAbbreviation, + addValueFactory: _ => new List<int> { unit }, + updateValueFactory: (_, existing) => existing.Append(unit).Distinct().ToList()); + } + + _unitToAbbreviationMap.AddOrUpdate(unit, + addValueFactory: _ => new List<string> { abbreviation }, + updateValueFactory: (_, existing) => + { + return setAsDefault + ? existing.Where(x => x != abbreviation).Prepend(abbreviation).ToList() + : existing.Where(x => x != abbreviation).Append(abbreviation).ToList(); + }); + + _allUnitAbbreviationsLazy = new Lazy<string[]>(ComputeAllUnitAbbreviationsValue); + } + } + + private string[] ComputeAllUnitAbbreviationsValue() + { + return _unitToAbbreviationMap.Values.SelectMany(abbreviations => abbreviations).Distinct().ToArray(); + } + } +} diff --git a/UnitsNet.Core/GeneratedCode/Quantity.g.cs b/UnitsNet.Core/GeneratedCode/Quantity.g.cs new file mode 100644 index 0000000000..627011fdea --- /dev/null +++ b/UnitsNet.Core/GeneratedCode/Quantity.g.cs @@ -0,0 +1,913 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Globalization; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +#nullable enable + +namespace UnitsNet +{ + /// <summary> + /// Dynamically parse or construct quantities when types are only known at runtime. + /// </summary> + public static partial class Quantity + { + // /// <summary> + // /// All QuantityInfo instances mapped by quantity name that are present in UnitsNet by default. + // /// </summary> + // public static readonly IDictionary<string, QuantityInfo> ByName = new Dictionary<string, QuantityInfo> + // { + // { "Acceleration", Acceleration.Info }, + // { "AmountOfSubstance", AmountOfSubstance.Info }, + // { "AmplitudeRatio", AmplitudeRatio.Info }, + // { "Angle", Angle.Info }, + // { "ApparentEnergy", ApparentEnergy.Info }, + // { "ApparentPower", ApparentPower.Info }, + // { "Area", Area.Info }, + // { "AreaDensity", AreaDensity.Info }, + // { "AreaMomentOfInertia", AreaMomentOfInertia.Info }, + // { "BitRate", BitRate.Info }, + // { "BrakeSpecificFuelConsumption", BrakeSpecificFuelConsumption.Info }, + // { "Capacitance", Capacitance.Info }, + // { "CoefficientOfThermalExpansion", CoefficientOfThermalExpansion.Info }, + // { "Compressibility", Compressibility.Info }, + // { "Density", Density.Info }, + // { "Duration", Duration.Info }, + // { "DynamicViscosity", DynamicViscosity.Info }, + // { "ElectricAdmittance", ElectricAdmittance.Info }, + // { "ElectricCharge", ElectricCharge.Info }, + // { "ElectricChargeDensity", ElectricChargeDensity.Info }, + // { "ElectricConductance", ElectricConductance.Info }, + // { "ElectricConductivity", ElectricConductivity.Info }, + // { "ElectricCurrent", ElectricCurrent.Info }, + // { "ElectricCurrentDensity", ElectricCurrentDensity.Info }, + // { "ElectricCurrentGradient", ElectricCurrentGradient.Info }, + // { "ElectricField", ElectricField.Info }, + // { "ElectricInductance", ElectricInductance.Info }, + // { "ElectricPotential", ElectricPotential.Info }, + // { "ElectricPotentialAc", ElectricPotentialAc.Info }, + // { "ElectricPotentialChangeRate", ElectricPotentialChangeRate.Info }, + // { "ElectricPotentialDc", ElectricPotentialDc.Info }, + // { "ElectricResistance", ElectricResistance.Info }, + // { "ElectricResistivity", ElectricResistivity.Info }, + // { "ElectricSurfaceChargeDensity", ElectricSurfaceChargeDensity.Info }, + // { "Energy", Energy.Info }, + // { "EnergyDensity", EnergyDensity.Info }, + // { "Entropy", Entropy.Info }, + // { "Force", Force.Info }, + // { "ForceChangeRate", ForceChangeRate.Info }, + // { "ForcePerLength", ForcePerLength.Info }, + // { "Frequency", Frequency.Info }, + // { "FuelEfficiency", FuelEfficiency.Info }, + // { "HeatFlux", HeatFlux.Info }, + // { "HeatTransferCoefficient", HeatTransferCoefficient.Info }, + // { "Illuminance", Illuminance.Info }, + // { "Information", Information.Info }, + // { "Irradiance", Irradiance.Info }, + // { "Irradiation", Irradiation.Info }, + // { "Jerk", Jerk.Info }, + // { "KinematicViscosity", KinematicViscosity.Info }, + // { "Length", Length.Info }, + // { "Level", Level.Info }, + // { "LinearDensity", LinearDensity.Info }, + // { "LinearPowerDensity", LinearPowerDensity.Info }, + // { "Luminance", Luminance.Info }, + // { "Luminosity", Luminosity.Info }, + // { "LuminousFlux", LuminousFlux.Info }, + // { "LuminousIntensity", LuminousIntensity.Info }, + // { "MagneticField", MagneticField.Info }, + // { "MagneticFlux", MagneticFlux.Info }, + // { "Magnetization", Magnetization.Info }, + // { "Mass", Mass.Info }, + // { "MassConcentration", MassConcentration.Info }, + // { "MassFlow", MassFlow.Info }, + // { "MassFlux", MassFlux.Info }, + // { "MassFraction", MassFraction.Info }, + // { "MassMomentOfInertia", MassMomentOfInertia.Info }, + // { "MolarEnergy", MolarEnergy.Info }, + // { "MolarEntropy", MolarEntropy.Info }, + // { "Molarity", Molarity.Info }, + // { "MolarMass", MolarMass.Info }, + // { "Permeability", Permeability.Info }, + // { "Permittivity", Permittivity.Info }, + // { "PorousMediumPermeability", PorousMediumPermeability.Info }, + // { "Power", Power.Info }, + // { "PowerDensity", PowerDensity.Info }, + // { "PowerRatio", PowerRatio.Info }, + // { "Pressure", Pressure.Info }, + // { "PressureChangeRate", PressureChangeRate.Info }, + // { "Ratio", Ratio.Info }, + // { "RatioChangeRate", RatioChangeRate.Info }, + // { "ReactiveEnergy", ReactiveEnergy.Info }, + // { "ReactivePower", ReactivePower.Info }, + // { "ReciprocalArea", ReciprocalArea.Info }, + // { "ReciprocalLength", ReciprocalLength.Info }, + // { "RelativeHumidity", RelativeHumidity.Info }, + // { "RotationalAcceleration", RotationalAcceleration.Info }, + // { "RotationalSpeed", RotationalSpeed.Info }, + // { "RotationalStiffness", RotationalStiffness.Info }, + // { "RotationalStiffnessPerLength", RotationalStiffnessPerLength.Info }, + // { "Scalar", Scalar.Info }, + // { "SolidAngle", SolidAngle.Info }, + // { "SpecificEnergy", SpecificEnergy.Info }, + // { "SpecificEntropy", SpecificEntropy.Info }, + // { "SpecificFuelConsumption", SpecificFuelConsumption.Info }, + // { "SpecificVolume", SpecificVolume.Info }, + // { "SpecificWeight", SpecificWeight.Info }, + // { "Speed", Speed.Info }, + // { "StandardVolumeFlow", StandardVolumeFlow.Info }, + // { "Temperature", Temperature.Info }, + // { "TemperatureChangeRate", TemperatureChangeRate.Info }, + // { "TemperatureDelta", TemperatureDelta.Info }, + // { "TemperatureGradient", TemperatureGradient.Info }, + // { "ThermalConductivity", ThermalConductivity.Info }, + // { "ThermalResistance", ThermalResistance.Info }, + // { "Torque", Torque.Info }, + // { "TorquePerLength", TorquePerLength.Info }, + // { "Turbidity", Turbidity.Info }, + // { "VitaminA", VitaminA.Info }, + // { "Volume", Volume.Info }, + // { "VolumeConcentration", VolumeConcentration.Info }, + // { "VolumeFlow", VolumeFlow.Info }, + // { "VolumeFlowPerArea", VolumeFlowPerArea.Info }, + // { "VolumePerLength", VolumePerLength.Info }, + // { "VolumetricHeatCapacity", VolumetricHeatCapacity.Info }, + // { "WarpingMomentOfInertia", WarpingMomentOfInertia.Info }, + // }; + // + // /// <summary> + // /// Dynamically constructs a quantity of the given <see cref="QuantityInfo"/> with the value in the quantity's base units. + // /// </summary> + // /// <param name="quantityInfo">The <see cref="QuantityInfo"/> of the quantity to create.</param> + // /// <param name="value">The value to construct the quantity with.</param> + // /// <returns>The created quantity.</returns> + // public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, QuantityValue value) + // { + // return quantityInfo.Name switch + // { + // "Acceleration" => Acceleration.From(value, Acceleration.BaseUnit), + // "AmountOfSubstance" => AmountOfSubstance.From(value, AmountOfSubstance.BaseUnit), + // "AmplitudeRatio" => AmplitudeRatio.From(value, AmplitudeRatio.BaseUnit), + // "Angle" => Angle.From(value, Angle.BaseUnit), + // "ApparentEnergy" => ApparentEnergy.From(value, ApparentEnergy.BaseUnit), + // "ApparentPower" => ApparentPower.From(value, ApparentPower.BaseUnit), + // "Area" => Area.From(value, Area.BaseUnit), + // "AreaDensity" => AreaDensity.From(value, AreaDensity.BaseUnit), + // "AreaMomentOfInertia" => AreaMomentOfInertia.From(value, AreaMomentOfInertia.BaseUnit), + // "BitRate" => BitRate.From(value, BitRate.BaseUnit), + // "BrakeSpecificFuelConsumption" => BrakeSpecificFuelConsumption.From(value, BrakeSpecificFuelConsumption.BaseUnit), + // "Capacitance" => Capacitance.From(value, Capacitance.BaseUnit), + // "CoefficientOfThermalExpansion" => CoefficientOfThermalExpansion.From(value, CoefficientOfThermalExpansion.BaseUnit), + // "Compressibility" => Compressibility.From(value, Compressibility.BaseUnit), + // "Density" => Density.From(value, Density.BaseUnit), + // "Duration" => Duration.From(value, Duration.BaseUnit), + // "DynamicViscosity" => DynamicViscosity.From(value, DynamicViscosity.BaseUnit), + // "ElectricAdmittance" => ElectricAdmittance.From(value, ElectricAdmittance.BaseUnit), + // "ElectricCharge" => ElectricCharge.From(value, ElectricCharge.BaseUnit), + // "ElectricChargeDensity" => ElectricChargeDensity.From(value, ElectricChargeDensity.BaseUnit), + // "ElectricConductance" => ElectricConductance.From(value, ElectricConductance.BaseUnit), + // "ElectricConductivity" => ElectricConductivity.From(value, ElectricConductivity.BaseUnit), + // "ElectricCurrent" => ElectricCurrent.From(value, ElectricCurrent.BaseUnit), + // "ElectricCurrentDensity" => ElectricCurrentDensity.From(value, ElectricCurrentDensity.BaseUnit), + // "ElectricCurrentGradient" => ElectricCurrentGradient.From(value, ElectricCurrentGradient.BaseUnit), + // "ElectricField" => ElectricField.From(value, ElectricField.BaseUnit), + // "ElectricInductance" => ElectricInductance.From(value, ElectricInductance.BaseUnit), + // "ElectricPotential" => ElectricPotential.From(value, ElectricPotential.BaseUnit), + // "ElectricPotentialAc" => ElectricPotentialAc.From(value, ElectricPotentialAc.BaseUnit), + // "ElectricPotentialChangeRate" => ElectricPotentialChangeRate.From(value, ElectricPotentialChangeRate.BaseUnit), + // "ElectricPotentialDc" => ElectricPotentialDc.From(value, ElectricPotentialDc.BaseUnit), + // "ElectricResistance" => ElectricResistance.From(value, ElectricResistance.BaseUnit), + // "ElectricResistivity" => ElectricResistivity.From(value, ElectricResistivity.BaseUnit), + // "ElectricSurfaceChargeDensity" => ElectricSurfaceChargeDensity.From(value, ElectricSurfaceChargeDensity.BaseUnit), + // "Energy" => Energy.From(value, Energy.BaseUnit), + // "EnergyDensity" => EnergyDensity.From(value, EnergyDensity.BaseUnit), + // "Entropy" => Entropy.From(value, Entropy.BaseUnit), + // "Force" => Force.From(value, Force.BaseUnit), + // "ForceChangeRate" => ForceChangeRate.From(value, ForceChangeRate.BaseUnit), + // "ForcePerLength" => ForcePerLength.From(value, ForcePerLength.BaseUnit), + // "Frequency" => Frequency.From(value, Frequency.BaseUnit), + // "FuelEfficiency" => FuelEfficiency.From(value, FuelEfficiency.BaseUnit), + // "HeatFlux" => HeatFlux.From(value, HeatFlux.BaseUnit), + // "HeatTransferCoefficient" => HeatTransferCoefficient.From(value, HeatTransferCoefficient.BaseUnit), + // "Illuminance" => Illuminance.From(value, Illuminance.BaseUnit), + // "Information" => Information.From(value, Information.BaseUnit), + // "Irradiance" => Irradiance.From(value, Irradiance.BaseUnit), + // "Irradiation" => Irradiation.From(value, Irradiation.BaseUnit), + // "Jerk" => Jerk.From(value, Jerk.BaseUnit), + // "KinematicViscosity" => KinematicViscosity.From(value, KinematicViscosity.BaseUnit), + // "Length" => Length.From(value, Length.BaseUnit), + // "Level" => Level.From(value, Level.BaseUnit), + // "LinearDensity" => LinearDensity.From(value, LinearDensity.BaseUnit), + // "LinearPowerDensity" => LinearPowerDensity.From(value, LinearPowerDensity.BaseUnit), + // "Luminance" => Luminance.From(value, Luminance.BaseUnit), + // "Luminosity" => Luminosity.From(value, Luminosity.BaseUnit), + // "LuminousFlux" => LuminousFlux.From(value, LuminousFlux.BaseUnit), + // "LuminousIntensity" => LuminousIntensity.From(value, LuminousIntensity.BaseUnit), + // "MagneticField" => MagneticField.From(value, MagneticField.BaseUnit), + // "MagneticFlux" => MagneticFlux.From(value, MagneticFlux.BaseUnit), + // "Magnetization" => Magnetization.From(value, Magnetization.BaseUnit), + // "Mass" => Mass.From(value, Mass.BaseUnit), + // "MassConcentration" => MassConcentration.From(value, MassConcentration.BaseUnit), + // "MassFlow" => MassFlow.From(value, MassFlow.BaseUnit), + // "MassFlux" => MassFlux.From(value, MassFlux.BaseUnit), + // "MassFraction" => MassFraction.From(value, MassFraction.BaseUnit), + // "MassMomentOfInertia" => MassMomentOfInertia.From(value, MassMomentOfInertia.BaseUnit), + // "MolarEnergy" => MolarEnergy.From(value, MolarEnergy.BaseUnit), + // "MolarEntropy" => MolarEntropy.From(value, MolarEntropy.BaseUnit), + // "Molarity" => Molarity.From(value, Molarity.BaseUnit), + // "MolarMass" => MolarMass.From(value, MolarMass.BaseUnit), + // "Permeability" => Permeability.From(value, Permeability.BaseUnit), + // "Permittivity" => Permittivity.From(value, Permittivity.BaseUnit), + // "PorousMediumPermeability" => PorousMediumPermeability.From(value, PorousMediumPermeability.BaseUnit), + // "Power" => Power.From(value, Power.BaseUnit), + // "PowerDensity" => PowerDensity.From(value, PowerDensity.BaseUnit), + // "PowerRatio" => PowerRatio.From(value, PowerRatio.BaseUnit), + // "Pressure" => Pressure.From(value, Pressure.BaseUnit), + // "PressureChangeRate" => PressureChangeRate.From(value, PressureChangeRate.BaseUnit), + // "Ratio" => Ratio.From(value, Ratio.BaseUnit), + // "RatioChangeRate" => RatioChangeRate.From(value, RatioChangeRate.BaseUnit), + // "ReactiveEnergy" => ReactiveEnergy.From(value, ReactiveEnergy.BaseUnit), + // "ReactivePower" => ReactivePower.From(value, ReactivePower.BaseUnit), + // "ReciprocalArea" => ReciprocalArea.From(value, ReciprocalArea.BaseUnit), + // "ReciprocalLength" => ReciprocalLength.From(value, ReciprocalLength.BaseUnit), + // "RelativeHumidity" => RelativeHumidity.From(value, RelativeHumidity.BaseUnit), + // "RotationalAcceleration" => RotationalAcceleration.From(value, RotationalAcceleration.BaseUnit), + // "RotationalSpeed" => RotationalSpeed.From(value, RotationalSpeed.BaseUnit), + // "RotationalStiffness" => RotationalStiffness.From(value, RotationalStiffness.BaseUnit), + // "RotationalStiffnessPerLength" => RotationalStiffnessPerLength.From(value, RotationalStiffnessPerLength.BaseUnit), + // "Scalar" => Scalar.From(value, Scalar.BaseUnit), + // "SolidAngle" => SolidAngle.From(value, SolidAngle.BaseUnit), + // "SpecificEnergy" => SpecificEnergy.From(value, SpecificEnergy.BaseUnit), + // "SpecificEntropy" => SpecificEntropy.From(value, SpecificEntropy.BaseUnit), + // "SpecificFuelConsumption" => SpecificFuelConsumption.From(value, SpecificFuelConsumption.BaseUnit), + // "SpecificVolume" => SpecificVolume.From(value, SpecificVolume.BaseUnit), + // "SpecificWeight" => SpecificWeight.From(value, SpecificWeight.BaseUnit), + // "Speed" => Speed.From(value, Speed.BaseUnit), + // "StandardVolumeFlow" => StandardVolumeFlow.From(value, StandardVolumeFlow.BaseUnit), + // "Temperature" => Temperature.From(value, Temperature.BaseUnit), + // "TemperatureChangeRate" => TemperatureChangeRate.From(value, TemperatureChangeRate.BaseUnit), + // "TemperatureDelta" => TemperatureDelta.From(value, TemperatureDelta.BaseUnit), + // "TemperatureGradient" => TemperatureGradient.From(value, TemperatureGradient.BaseUnit), + // "ThermalConductivity" => ThermalConductivity.From(value, ThermalConductivity.BaseUnit), + // "ThermalResistance" => ThermalResistance.From(value, ThermalResistance.BaseUnit), + // "Torque" => Torque.From(value, Torque.BaseUnit), + // "TorquePerLength" => TorquePerLength.From(value, TorquePerLength.BaseUnit), + // "Turbidity" => Turbidity.From(value, Turbidity.BaseUnit), + // "VitaminA" => VitaminA.From(value, VitaminA.BaseUnit), + // "Volume" => Volume.From(value, Volume.BaseUnit), + // "VolumeConcentration" => VolumeConcentration.From(value, VolumeConcentration.BaseUnit), + // "VolumeFlow" => VolumeFlow.From(value, VolumeFlow.BaseUnit), + // "VolumeFlowPerArea" => VolumeFlowPerArea.From(value, VolumeFlowPerArea.BaseUnit), + // "VolumePerLength" => VolumePerLength.From(value, VolumePerLength.BaseUnit), + // "VolumetricHeatCapacity" => VolumetricHeatCapacity.From(value, VolumetricHeatCapacity.BaseUnit), + // "WarpingMomentOfInertia" => WarpingMomentOfInertia.From(value, WarpingMomentOfInertia.BaseUnit), + // _ => throw new ArgumentException($"{quantityInfo.Name} is not a supported quantity.") + // }; + // } + // + // /// <summary> + // /// Try to dynamically construct a quantity. + // /// </summary> + // /// <param name="value">Numeric value.</param> + // /// <param name="unit">Unit enum value.</param> + // /// <param name="quantity">The resulting quantity if successful, otherwise <c>default</c>.</param> + // /// <returns><c>True</c> if successful with <paramref name="quantity"/> assigned the value, otherwise <c>false</c>.</returns> + // public static bool TryFrom(QuantityValue value, Enum unit, [NotNullWhen(true)] out IQuantity? quantity) + // { + // switch (unit) + // { + // case AccelerationUnit accelerationUnit: + // quantity = Acceleration.From(value, accelerationUnit); + // return true; + // case AmountOfSubstanceUnit amountOfSubstanceUnit: + // quantity = AmountOfSubstance.From(value, amountOfSubstanceUnit); + // return true; + // case AmplitudeRatioUnit amplitudeRatioUnit: + // quantity = AmplitudeRatio.From(value, amplitudeRatioUnit); + // return true; + // case AngleUnit angleUnit: + // quantity = Angle.From(value, angleUnit); + // return true; + // case ApparentEnergyUnit apparentEnergyUnit: + // quantity = ApparentEnergy.From(value, apparentEnergyUnit); + // return true; + // case ApparentPowerUnit apparentPowerUnit: + // quantity = ApparentPower.From(value, apparentPowerUnit); + // return true; + // case AreaUnit areaUnit: + // quantity = Area.From(value, areaUnit); + // return true; + // case AreaDensityUnit areaDensityUnit: + // quantity = AreaDensity.From(value, areaDensityUnit); + // return true; + // case AreaMomentOfInertiaUnit areaMomentOfInertiaUnit: + // quantity = AreaMomentOfInertia.From(value, areaMomentOfInertiaUnit); + // return true; + // case BitRateUnit bitRateUnit: + // quantity = BitRate.From(value, bitRateUnit); + // return true; + // case BrakeSpecificFuelConsumptionUnit brakeSpecificFuelConsumptionUnit: + // quantity = BrakeSpecificFuelConsumption.From(value, brakeSpecificFuelConsumptionUnit); + // return true; + // case CapacitanceUnit capacitanceUnit: + // quantity = Capacitance.From(value, capacitanceUnit); + // return true; + // case CoefficientOfThermalExpansionUnit coefficientOfThermalExpansionUnit: + // quantity = CoefficientOfThermalExpansion.From(value, coefficientOfThermalExpansionUnit); + // return true; + // case CompressibilityUnit compressibilityUnit: + // quantity = Compressibility.From(value, compressibilityUnit); + // return true; + // case DensityUnit densityUnit: + // quantity = Density.From(value, densityUnit); + // return true; + // case DurationUnit durationUnit: + // quantity = Duration.From(value, durationUnit); + // return true; + // case DynamicViscosityUnit dynamicViscosityUnit: + // quantity = DynamicViscosity.From(value, dynamicViscosityUnit); + // return true; + // case ElectricAdmittanceUnit electricAdmittanceUnit: + // quantity = ElectricAdmittance.From(value, electricAdmittanceUnit); + // return true; + // case ElectricChargeUnit electricChargeUnit: + // quantity = ElectricCharge.From(value, electricChargeUnit); + // return true; + // case ElectricChargeDensityUnit electricChargeDensityUnit: + // quantity = ElectricChargeDensity.From(value, electricChargeDensityUnit); + // return true; + // case ElectricConductanceUnit electricConductanceUnit: + // quantity = ElectricConductance.From(value, electricConductanceUnit); + // return true; + // case ElectricConductivityUnit electricConductivityUnit: + // quantity = ElectricConductivity.From(value, electricConductivityUnit); + // return true; + // case ElectricCurrentUnit electricCurrentUnit: + // quantity = ElectricCurrent.From(value, electricCurrentUnit); + // return true; + // case ElectricCurrentDensityUnit electricCurrentDensityUnit: + // quantity = ElectricCurrentDensity.From(value, electricCurrentDensityUnit); + // return true; + // case ElectricCurrentGradientUnit electricCurrentGradientUnit: + // quantity = ElectricCurrentGradient.From(value, electricCurrentGradientUnit); + // return true; + // case ElectricFieldUnit electricFieldUnit: + // quantity = ElectricField.From(value, electricFieldUnit); + // return true; + // case ElectricInductanceUnit electricInductanceUnit: + // quantity = ElectricInductance.From(value, electricInductanceUnit); + // return true; + // case ElectricPotentialUnit electricPotentialUnit: + // quantity = ElectricPotential.From(value, electricPotentialUnit); + // return true; + // case ElectricPotentialAcUnit electricPotentialAcUnit: + // quantity = ElectricPotentialAc.From(value, electricPotentialAcUnit); + // return true; + // case ElectricPotentialChangeRateUnit electricPotentialChangeRateUnit: + // quantity = ElectricPotentialChangeRate.From(value, electricPotentialChangeRateUnit); + // return true; + // case ElectricPotentialDcUnit electricPotentialDcUnit: + // quantity = ElectricPotentialDc.From(value, electricPotentialDcUnit); + // return true; + // case ElectricResistanceUnit electricResistanceUnit: + // quantity = ElectricResistance.From(value, electricResistanceUnit); + // return true; + // case ElectricResistivityUnit electricResistivityUnit: + // quantity = ElectricResistivity.From(value, electricResistivityUnit); + // return true; + // case ElectricSurfaceChargeDensityUnit electricSurfaceChargeDensityUnit: + // quantity = ElectricSurfaceChargeDensity.From(value, electricSurfaceChargeDensityUnit); + // return true; + // case EnergyUnit energyUnit: + // quantity = Energy.From(value, energyUnit); + // return true; + // case EnergyDensityUnit energyDensityUnit: + // quantity = EnergyDensity.From(value, energyDensityUnit); + // return true; + // case EntropyUnit entropyUnit: + // quantity = Entropy.From(value, entropyUnit); + // return true; + // case ForceUnit forceUnit: + // quantity = Force.From(value, forceUnit); + // return true; + // case ForceChangeRateUnit forceChangeRateUnit: + // quantity = ForceChangeRate.From(value, forceChangeRateUnit); + // return true; + // case ForcePerLengthUnit forcePerLengthUnit: + // quantity = ForcePerLength.From(value, forcePerLengthUnit); + // return true; + // case FrequencyUnit frequencyUnit: + // quantity = Frequency.From(value, frequencyUnit); + // return true; + // case FuelEfficiencyUnit fuelEfficiencyUnit: + // quantity = FuelEfficiency.From(value, fuelEfficiencyUnit); + // return true; + // case HeatFluxUnit heatFluxUnit: + // quantity = HeatFlux.From(value, heatFluxUnit); + // return true; + // case HeatTransferCoefficientUnit heatTransferCoefficientUnit: + // quantity = HeatTransferCoefficient.From(value, heatTransferCoefficientUnit); + // return true; + // case IlluminanceUnit illuminanceUnit: + // quantity = Illuminance.From(value, illuminanceUnit); + // return true; + // case InformationUnit informationUnit: + // quantity = Information.From(value, informationUnit); + // return true; + // case IrradianceUnit irradianceUnit: + // quantity = Irradiance.From(value, irradianceUnit); + // return true; + // case IrradiationUnit irradiationUnit: + // quantity = Irradiation.From(value, irradiationUnit); + // return true; + // case JerkUnit jerkUnit: + // quantity = Jerk.From(value, jerkUnit); + // return true; + // case KinematicViscosityUnit kinematicViscosityUnit: + // quantity = KinematicViscosity.From(value, kinematicViscosityUnit); + // return true; + // case LengthUnit lengthUnit: + // quantity = Length.From(value, lengthUnit); + // return true; + // case LevelUnit levelUnit: + // quantity = Level.From(value, levelUnit); + // return true; + // case LinearDensityUnit linearDensityUnit: + // quantity = LinearDensity.From(value, linearDensityUnit); + // return true; + // case LinearPowerDensityUnit linearPowerDensityUnit: + // quantity = LinearPowerDensity.From(value, linearPowerDensityUnit); + // return true; + // case LuminanceUnit luminanceUnit: + // quantity = Luminance.From(value, luminanceUnit); + // return true; + // case LuminosityUnit luminosityUnit: + // quantity = Luminosity.From(value, luminosityUnit); + // return true; + // case LuminousFluxUnit luminousFluxUnit: + // quantity = LuminousFlux.From(value, luminousFluxUnit); + // return true; + // case LuminousIntensityUnit luminousIntensityUnit: + // quantity = LuminousIntensity.From(value, luminousIntensityUnit); + // return true; + // case MagneticFieldUnit magneticFieldUnit: + // quantity = MagneticField.From(value, magneticFieldUnit); + // return true; + // case MagneticFluxUnit magneticFluxUnit: + // quantity = MagneticFlux.From(value, magneticFluxUnit); + // return true; + // case MagnetizationUnit magnetizationUnit: + // quantity = Magnetization.From(value, magnetizationUnit); + // return true; + // case MassUnit massUnit: + // quantity = Mass.From(value, massUnit); + // return true; + // case MassConcentrationUnit massConcentrationUnit: + // quantity = MassConcentration.From(value, massConcentrationUnit); + // return true; + // case MassFlowUnit massFlowUnit: + // quantity = MassFlow.From(value, massFlowUnit); + // return true; + // case MassFluxUnit massFluxUnit: + // quantity = MassFlux.From(value, massFluxUnit); + // return true; + // case MassFractionUnit massFractionUnit: + // quantity = MassFraction.From(value, massFractionUnit); + // return true; + // case MassMomentOfInertiaUnit massMomentOfInertiaUnit: + // quantity = MassMomentOfInertia.From(value, massMomentOfInertiaUnit); + // return true; + // case MolarEnergyUnit molarEnergyUnit: + // quantity = MolarEnergy.From(value, molarEnergyUnit); + // return true; + // case MolarEntropyUnit molarEntropyUnit: + // quantity = MolarEntropy.From(value, molarEntropyUnit); + // return true; + // case MolarityUnit molarityUnit: + // quantity = Molarity.From(value, molarityUnit); + // return true; + // case MolarMassUnit molarMassUnit: + // quantity = MolarMass.From(value, molarMassUnit); + // return true; + // case PermeabilityUnit permeabilityUnit: + // quantity = Permeability.From(value, permeabilityUnit); + // return true; + // case PermittivityUnit permittivityUnit: + // quantity = Permittivity.From(value, permittivityUnit); + // return true; + // case PorousMediumPermeabilityUnit porousMediumPermeabilityUnit: + // quantity = PorousMediumPermeability.From(value, porousMediumPermeabilityUnit); + // return true; + // case PowerUnit powerUnit: + // quantity = Power.From(value, powerUnit); + // return true; + // case PowerDensityUnit powerDensityUnit: + // quantity = PowerDensity.From(value, powerDensityUnit); + // return true; + // case PowerRatioUnit powerRatioUnit: + // quantity = PowerRatio.From(value, powerRatioUnit); + // return true; + // case PressureUnit pressureUnit: + // quantity = Pressure.From(value, pressureUnit); + // return true; + // case PressureChangeRateUnit pressureChangeRateUnit: + // quantity = PressureChangeRate.From(value, pressureChangeRateUnit); + // return true; + // case RatioUnit ratioUnit: + // quantity = Ratio.From(value, ratioUnit); + // return true; + // case RatioChangeRateUnit ratioChangeRateUnit: + // quantity = RatioChangeRate.From(value, ratioChangeRateUnit); + // return true; + // case ReactiveEnergyUnit reactiveEnergyUnit: + // quantity = ReactiveEnergy.From(value, reactiveEnergyUnit); + // return true; + // case ReactivePowerUnit reactivePowerUnit: + // quantity = ReactivePower.From(value, reactivePowerUnit); + // return true; + // case ReciprocalAreaUnit reciprocalAreaUnit: + // quantity = ReciprocalArea.From(value, reciprocalAreaUnit); + // return true; + // case ReciprocalLengthUnit reciprocalLengthUnit: + // quantity = ReciprocalLength.From(value, reciprocalLengthUnit); + // return true; + // case RelativeHumidityUnit relativeHumidityUnit: + // quantity = RelativeHumidity.From(value, relativeHumidityUnit); + // return true; + // case RotationalAccelerationUnit rotationalAccelerationUnit: + // quantity = RotationalAcceleration.From(value, rotationalAccelerationUnit); + // return true; + // case RotationalSpeedUnit rotationalSpeedUnit: + // quantity = RotationalSpeed.From(value, rotationalSpeedUnit); + // return true; + // case RotationalStiffnessUnit rotationalStiffnessUnit: + // quantity = RotationalStiffness.From(value, rotationalStiffnessUnit); + // return true; + // case RotationalStiffnessPerLengthUnit rotationalStiffnessPerLengthUnit: + // quantity = RotationalStiffnessPerLength.From(value, rotationalStiffnessPerLengthUnit); + // return true; + // case ScalarUnit scalarUnit: + // quantity = Scalar.From(value, scalarUnit); + // return true; + // case SolidAngleUnit solidAngleUnit: + // quantity = SolidAngle.From(value, solidAngleUnit); + // return true; + // case SpecificEnergyUnit specificEnergyUnit: + // quantity = SpecificEnergy.From(value, specificEnergyUnit); + // return true; + // case SpecificEntropyUnit specificEntropyUnit: + // quantity = SpecificEntropy.From(value, specificEntropyUnit); + // return true; + // case SpecificFuelConsumptionUnit specificFuelConsumptionUnit: + // quantity = SpecificFuelConsumption.From(value, specificFuelConsumptionUnit); + // return true; + // case SpecificVolumeUnit specificVolumeUnit: + // quantity = SpecificVolume.From(value, specificVolumeUnit); + // return true; + // case SpecificWeightUnit specificWeightUnit: + // quantity = SpecificWeight.From(value, specificWeightUnit); + // return true; + // case SpeedUnit speedUnit: + // quantity = Speed.From(value, speedUnit); + // return true; + // case StandardVolumeFlowUnit standardVolumeFlowUnit: + // quantity = StandardVolumeFlow.From(value, standardVolumeFlowUnit); + // return true; + // case TemperatureUnit temperatureUnit: + // quantity = Temperature.From(value, temperatureUnit); + // return true; + // case TemperatureChangeRateUnit temperatureChangeRateUnit: + // quantity = TemperatureChangeRate.From(value, temperatureChangeRateUnit); + // return true; + // case TemperatureDeltaUnit temperatureDeltaUnit: + // quantity = TemperatureDelta.From(value, temperatureDeltaUnit); + // return true; + // case TemperatureGradientUnit temperatureGradientUnit: + // quantity = TemperatureGradient.From(value, temperatureGradientUnit); + // return true; + // case ThermalConductivityUnit thermalConductivityUnit: + // quantity = ThermalConductivity.From(value, thermalConductivityUnit); + // return true; + // case ThermalResistanceUnit thermalResistanceUnit: + // quantity = ThermalResistance.From(value, thermalResistanceUnit); + // return true; + // case TorqueUnit torqueUnit: + // quantity = Torque.From(value, torqueUnit); + // return true; + // case TorquePerLengthUnit torquePerLengthUnit: + // quantity = TorquePerLength.From(value, torquePerLengthUnit); + // return true; + // case TurbidityUnit turbidityUnit: + // quantity = Turbidity.From(value, turbidityUnit); + // return true; + // case VitaminAUnit vitaminAUnit: + // quantity = VitaminA.From(value, vitaminAUnit); + // return true; + // case VolumeUnit volumeUnit: + // quantity = Volume.From(value, volumeUnit); + // return true; + // case VolumeConcentrationUnit volumeConcentrationUnit: + // quantity = VolumeConcentration.From(value, volumeConcentrationUnit); + // return true; + // case VolumeFlowUnit volumeFlowUnit: + // quantity = VolumeFlow.From(value, volumeFlowUnit); + // return true; + // case VolumeFlowPerAreaUnit volumeFlowPerAreaUnit: + // quantity = VolumeFlowPerArea.From(value, volumeFlowPerAreaUnit); + // return true; + // case VolumePerLengthUnit volumePerLengthUnit: + // quantity = VolumePerLength.From(value, volumePerLengthUnit); + // return true; + // case VolumetricHeatCapacityUnit volumetricHeatCapacityUnit: + // quantity = VolumetricHeatCapacity.From(value, volumetricHeatCapacityUnit); + // return true; + // case WarpingMomentOfInertiaUnit warpingMomentOfInertiaUnit: + // quantity = WarpingMomentOfInertia.From(value, warpingMomentOfInertiaUnit); + // return true; + // default: + // { + // quantity = default(IQuantity); + // return false; + // } + // } + // } + // + // /// <summary> + // /// Try to dynamically parse a quantity string representation. + // /// </summary> + // /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + // /// <param name="quantityType">Type of quantity, such as <see cref="Length"/>.</param> + // /// <param name="quantityString">Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type.</param> + // /// <param name="quantity">The resulting quantity if successful, otherwise <c>default</c>.</param> + // /// <returns>The parsed quantity.</returns> + // public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, string quantityString, [NotNullWhen(true)] out IQuantity? quantity) + // { + // quantity = default(IQuantity); + // + // if (!typeof(IQuantity).IsAssignableFrom(quantityType)) + // return false; + // + // var parser = QuantityParser.Default; + // + // return quantityType switch + // { + // Type _ when quantityType == typeof(Acceleration) => parser.TryParse<Acceleration, AccelerationUnit>(quantityString, formatProvider, Acceleration.From, out quantity), + // Type _ when quantityType == typeof(AmountOfSubstance) => parser.TryParse<AmountOfSubstance, AmountOfSubstanceUnit>(quantityString, formatProvider, AmountOfSubstance.From, out quantity), + // Type _ when quantityType == typeof(AmplitudeRatio) => parser.TryParse<AmplitudeRatio, AmplitudeRatioUnit>(quantityString, formatProvider, AmplitudeRatio.From, out quantity), + // Type _ when quantityType == typeof(Angle) => parser.TryParse<Angle, AngleUnit>(quantityString, formatProvider, Angle.From, out quantity), + // Type _ when quantityType == typeof(ApparentEnergy) => parser.TryParse<ApparentEnergy, ApparentEnergyUnit>(quantityString, formatProvider, ApparentEnergy.From, out quantity), + // Type _ when quantityType == typeof(ApparentPower) => parser.TryParse<ApparentPower, ApparentPowerUnit>(quantityString, formatProvider, ApparentPower.From, out quantity), + // Type _ when quantityType == typeof(Area) => parser.TryParse<Area, AreaUnit>(quantityString, formatProvider, Area.From, out quantity), + // Type _ when quantityType == typeof(AreaDensity) => parser.TryParse<AreaDensity, AreaDensityUnit>(quantityString, formatProvider, AreaDensity.From, out quantity), + // Type _ when quantityType == typeof(AreaMomentOfInertia) => parser.TryParse<AreaMomentOfInertia, AreaMomentOfInertiaUnit>(quantityString, formatProvider, AreaMomentOfInertia.From, out quantity), + // Type _ when quantityType == typeof(BitRate) => parser.TryParse<BitRate, BitRateUnit>(quantityString, formatProvider, BitRate.From, out quantity), + // Type _ when quantityType == typeof(BrakeSpecificFuelConsumption) => parser.TryParse<BrakeSpecificFuelConsumption, BrakeSpecificFuelConsumptionUnit>(quantityString, formatProvider, BrakeSpecificFuelConsumption.From, out quantity), + // Type _ when quantityType == typeof(Capacitance) => parser.TryParse<Capacitance, CapacitanceUnit>(quantityString, formatProvider, Capacitance.From, out quantity), + // Type _ when quantityType == typeof(CoefficientOfThermalExpansion) => parser.TryParse<CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit>(quantityString, formatProvider, CoefficientOfThermalExpansion.From, out quantity), + // Type _ when quantityType == typeof(Compressibility) => parser.TryParse<Compressibility, CompressibilityUnit>(quantityString, formatProvider, Compressibility.From, out quantity), + // Type _ when quantityType == typeof(Density) => parser.TryParse<Density, DensityUnit>(quantityString, formatProvider, Density.From, out quantity), + // Type _ when quantityType == typeof(Duration) => parser.TryParse<Duration, DurationUnit>(quantityString, formatProvider, Duration.From, out quantity), + // Type _ when quantityType == typeof(DynamicViscosity) => parser.TryParse<DynamicViscosity, DynamicViscosityUnit>(quantityString, formatProvider, DynamicViscosity.From, out quantity), + // Type _ when quantityType == typeof(ElectricAdmittance) => parser.TryParse<ElectricAdmittance, ElectricAdmittanceUnit>(quantityString, formatProvider, ElectricAdmittance.From, out quantity), + // Type _ when quantityType == typeof(ElectricCharge) => parser.TryParse<ElectricCharge, ElectricChargeUnit>(quantityString, formatProvider, ElectricCharge.From, out quantity), + // Type _ when quantityType == typeof(ElectricChargeDensity) => parser.TryParse<ElectricChargeDensity, ElectricChargeDensityUnit>(quantityString, formatProvider, ElectricChargeDensity.From, out quantity), + // Type _ when quantityType == typeof(ElectricConductance) => parser.TryParse<ElectricConductance, ElectricConductanceUnit>(quantityString, formatProvider, ElectricConductance.From, out quantity), + // Type _ when quantityType == typeof(ElectricConductivity) => parser.TryParse<ElectricConductivity, ElectricConductivityUnit>(quantityString, formatProvider, ElectricConductivity.From, out quantity), + // Type _ when quantityType == typeof(ElectricCurrent) => parser.TryParse<ElectricCurrent, ElectricCurrentUnit>(quantityString, formatProvider, ElectricCurrent.From, out quantity), + // Type _ when quantityType == typeof(ElectricCurrentDensity) => parser.TryParse<ElectricCurrentDensity, ElectricCurrentDensityUnit>(quantityString, formatProvider, ElectricCurrentDensity.From, out quantity), + // Type _ when quantityType == typeof(ElectricCurrentGradient) => parser.TryParse<ElectricCurrentGradient, ElectricCurrentGradientUnit>(quantityString, formatProvider, ElectricCurrentGradient.From, out quantity), + // Type _ when quantityType == typeof(ElectricField) => parser.TryParse<ElectricField, ElectricFieldUnit>(quantityString, formatProvider, ElectricField.From, out quantity), + // Type _ when quantityType == typeof(ElectricInductance) => parser.TryParse<ElectricInductance, ElectricInductanceUnit>(quantityString, formatProvider, ElectricInductance.From, out quantity), + // Type _ when quantityType == typeof(ElectricPotential) => parser.TryParse<ElectricPotential, ElectricPotentialUnit>(quantityString, formatProvider, ElectricPotential.From, out quantity), + // Type _ when quantityType == typeof(ElectricPotentialAc) => parser.TryParse<ElectricPotentialAc, ElectricPotentialAcUnit>(quantityString, formatProvider, ElectricPotentialAc.From, out quantity), + // Type _ when quantityType == typeof(ElectricPotentialChangeRate) => parser.TryParse<ElectricPotentialChangeRate, ElectricPotentialChangeRateUnit>(quantityString, formatProvider, ElectricPotentialChangeRate.From, out quantity), + // Type _ when quantityType == typeof(ElectricPotentialDc) => parser.TryParse<ElectricPotentialDc, ElectricPotentialDcUnit>(quantityString, formatProvider, ElectricPotentialDc.From, out quantity), + // Type _ when quantityType == typeof(ElectricResistance) => parser.TryParse<ElectricResistance, ElectricResistanceUnit>(quantityString, formatProvider, ElectricResistance.From, out quantity), + // Type _ when quantityType == typeof(ElectricResistivity) => parser.TryParse<ElectricResistivity, ElectricResistivityUnit>(quantityString, formatProvider, ElectricResistivity.From, out quantity), + // Type _ when quantityType == typeof(ElectricSurfaceChargeDensity) => parser.TryParse<ElectricSurfaceChargeDensity, ElectricSurfaceChargeDensityUnit>(quantityString, formatProvider, ElectricSurfaceChargeDensity.From, out quantity), + // Type _ when quantityType == typeof(Energy) => parser.TryParse<Energy, EnergyUnit>(quantityString, formatProvider, Energy.From, out quantity), + // Type _ when quantityType == typeof(EnergyDensity) => parser.TryParse<EnergyDensity, EnergyDensityUnit>(quantityString, formatProvider, EnergyDensity.From, out quantity), + // Type _ when quantityType == typeof(Entropy) => parser.TryParse<Entropy, EntropyUnit>(quantityString, formatProvider, Entropy.From, out quantity), + // Type _ when quantityType == typeof(Force) => parser.TryParse<Force, ForceUnit>(quantityString, formatProvider, Force.From, out quantity), + // Type _ when quantityType == typeof(ForceChangeRate) => parser.TryParse<ForceChangeRate, ForceChangeRateUnit>(quantityString, formatProvider, ForceChangeRate.From, out quantity), + // Type _ when quantityType == typeof(ForcePerLength) => parser.TryParse<ForcePerLength, ForcePerLengthUnit>(quantityString, formatProvider, ForcePerLength.From, out quantity), + // Type _ when quantityType == typeof(Frequency) => parser.TryParse<Frequency, FrequencyUnit>(quantityString, formatProvider, Frequency.From, out quantity), + // Type _ when quantityType == typeof(FuelEfficiency) => parser.TryParse<FuelEfficiency, FuelEfficiencyUnit>(quantityString, formatProvider, FuelEfficiency.From, out quantity), + // Type _ when quantityType == typeof(HeatFlux) => parser.TryParse<HeatFlux, HeatFluxUnit>(quantityString, formatProvider, HeatFlux.From, out quantity), + // Type _ when quantityType == typeof(HeatTransferCoefficient) => parser.TryParse<HeatTransferCoefficient, HeatTransferCoefficientUnit>(quantityString, formatProvider, HeatTransferCoefficient.From, out quantity), + // Type _ when quantityType == typeof(Illuminance) => parser.TryParse<Illuminance, IlluminanceUnit>(quantityString, formatProvider, Illuminance.From, out quantity), + // Type _ when quantityType == typeof(Information) => parser.TryParse<Information, InformationUnit>(quantityString, formatProvider, Information.From, out quantity), + // Type _ when quantityType == typeof(Irradiance) => parser.TryParse<Irradiance, IrradianceUnit>(quantityString, formatProvider, Irradiance.From, out quantity), + // Type _ when quantityType == typeof(Irradiation) => parser.TryParse<Irradiation, IrradiationUnit>(quantityString, formatProvider, Irradiation.From, out quantity), + // Type _ when quantityType == typeof(Jerk) => parser.TryParse<Jerk, JerkUnit>(quantityString, formatProvider, Jerk.From, out quantity), + // Type _ when quantityType == typeof(KinematicViscosity) => parser.TryParse<KinematicViscosity, KinematicViscosityUnit>(quantityString, formatProvider, KinematicViscosity.From, out quantity), + // Type _ when quantityType == typeof(Length) => parser.TryParse<Length, LengthUnit>(quantityString, formatProvider, Length.From, out quantity), + // Type _ when quantityType == typeof(Level) => parser.TryParse<Level, LevelUnit>(quantityString, formatProvider, Level.From, out quantity), + // Type _ when quantityType == typeof(LinearDensity) => parser.TryParse<LinearDensity, LinearDensityUnit>(quantityString, formatProvider, LinearDensity.From, out quantity), + // Type _ when quantityType == typeof(LinearPowerDensity) => parser.TryParse<LinearPowerDensity, LinearPowerDensityUnit>(quantityString, formatProvider, LinearPowerDensity.From, out quantity), + // Type _ when quantityType == typeof(Luminance) => parser.TryParse<Luminance, LuminanceUnit>(quantityString, formatProvider, Luminance.From, out quantity), + // Type _ when quantityType == typeof(Luminosity) => parser.TryParse<Luminosity, LuminosityUnit>(quantityString, formatProvider, Luminosity.From, out quantity), + // Type _ when quantityType == typeof(LuminousFlux) => parser.TryParse<LuminousFlux, LuminousFluxUnit>(quantityString, formatProvider, LuminousFlux.From, out quantity), + // Type _ when quantityType == typeof(LuminousIntensity) => parser.TryParse<LuminousIntensity, LuminousIntensityUnit>(quantityString, formatProvider, LuminousIntensity.From, out quantity), + // Type _ when quantityType == typeof(MagneticField) => parser.TryParse<MagneticField, MagneticFieldUnit>(quantityString, formatProvider, MagneticField.From, out quantity), + // Type _ when quantityType == typeof(MagneticFlux) => parser.TryParse<MagneticFlux, MagneticFluxUnit>(quantityString, formatProvider, MagneticFlux.From, out quantity), + // Type _ when quantityType == typeof(Magnetization) => parser.TryParse<Magnetization, MagnetizationUnit>(quantityString, formatProvider, Magnetization.From, out quantity), + // Type _ when quantityType == typeof(Mass) => parser.TryParse<Mass, MassUnit>(quantityString, formatProvider, Mass.From, out quantity), + // Type _ when quantityType == typeof(MassConcentration) => parser.TryParse<MassConcentration, MassConcentrationUnit>(quantityString, formatProvider, MassConcentration.From, out quantity), + // Type _ when quantityType == typeof(MassFlow) => parser.TryParse<MassFlow, MassFlowUnit>(quantityString, formatProvider, MassFlow.From, out quantity), + // Type _ when quantityType == typeof(MassFlux) => parser.TryParse<MassFlux, MassFluxUnit>(quantityString, formatProvider, MassFlux.From, out quantity), + // Type _ when quantityType == typeof(MassFraction) => parser.TryParse<MassFraction, MassFractionUnit>(quantityString, formatProvider, MassFraction.From, out quantity), + // Type _ when quantityType == typeof(MassMomentOfInertia) => parser.TryParse<MassMomentOfInertia, MassMomentOfInertiaUnit>(quantityString, formatProvider, MassMomentOfInertia.From, out quantity), + // Type _ when quantityType == typeof(MolarEnergy) => parser.TryParse<MolarEnergy, MolarEnergyUnit>(quantityString, formatProvider, MolarEnergy.From, out quantity), + // Type _ when quantityType == typeof(MolarEntropy) => parser.TryParse<MolarEntropy, MolarEntropyUnit>(quantityString, formatProvider, MolarEntropy.From, out quantity), + // Type _ when quantityType == typeof(Molarity) => parser.TryParse<Molarity, MolarityUnit>(quantityString, formatProvider, Molarity.From, out quantity), + // Type _ when quantityType == typeof(MolarMass) => parser.TryParse<MolarMass, MolarMassUnit>(quantityString, formatProvider, MolarMass.From, out quantity), + // Type _ when quantityType == typeof(Permeability) => parser.TryParse<Permeability, PermeabilityUnit>(quantityString, formatProvider, Permeability.From, out quantity), + // Type _ when quantityType == typeof(Permittivity) => parser.TryParse<Permittivity, PermittivityUnit>(quantityString, formatProvider, Permittivity.From, out quantity), + // Type _ when quantityType == typeof(PorousMediumPermeability) => parser.TryParse<PorousMediumPermeability, PorousMediumPermeabilityUnit>(quantityString, formatProvider, PorousMediumPermeability.From, out quantity), + // Type _ when quantityType == typeof(Power) => parser.TryParse<Power, PowerUnit>(quantityString, formatProvider, Power.From, out quantity), + // Type _ when quantityType == typeof(PowerDensity) => parser.TryParse<PowerDensity, PowerDensityUnit>(quantityString, formatProvider, PowerDensity.From, out quantity), + // Type _ when quantityType == typeof(PowerRatio) => parser.TryParse<PowerRatio, PowerRatioUnit>(quantityString, formatProvider, PowerRatio.From, out quantity), + // Type _ when quantityType == typeof(Pressure) => parser.TryParse<Pressure, PressureUnit>(quantityString, formatProvider, Pressure.From, out quantity), + // Type _ when quantityType == typeof(PressureChangeRate) => parser.TryParse<PressureChangeRate, PressureChangeRateUnit>(quantityString, formatProvider, PressureChangeRate.From, out quantity), + // Type _ when quantityType == typeof(Ratio) => parser.TryParse<Ratio, RatioUnit>(quantityString, formatProvider, Ratio.From, out quantity), + // Type _ when quantityType == typeof(RatioChangeRate) => parser.TryParse<RatioChangeRate, RatioChangeRateUnit>(quantityString, formatProvider, RatioChangeRate.From, out quantity), + // Type _ when quantityType == typeof(ReactiveEnergy) => parser.TryParse<ReactiveEnergy, ReactiveEnergyUnit>(quantityString, formatProvider, ReactiveEnergy.From, out quantity), + // Type _ when quantityType == typeof(ReactivePower) => parser.TryParse<ReactivePower, ReactivePowerUnit>(quantityString, formatProvider, ReactivePower.From, out quantity), + // Type _ when quantityType == typeof(ReciprocalArea) => parser.TryParse<ReciprocalArea, ReciprocalAreaUnit>(quantityString, formatProvider, ReciprocalArea.From, out quantity), + // Type _ when quantityType == typeof(ReciprocalLength) => parser.TryParse<ReciprocalLength, ReciprocalLengthUnit>(quantityString, formatProvider, ReciprocalLength.From, out quantity), + // Type _ when quantityType == typeof(RelativeHumidity) => parser.TryParse<RelativeHumidity, RelativeHumidityUnit>(quantityString, formatProvider, RelativeHumidity.From, out quantity), + // Type _ when quantityType == typeof(RotationalAcceleration) => parser.TryParse<RotationalAcceleration, RotationalAccelerationUnit>(quantityString, formatProvider, RotationalAcceleration.From, out quantity), + // Type _ when quantityType == typeof(RotationalSpeed) => parser.TryParse<RotationalSpeed, RotationalSpeedUnit>(quantityString, formatProvider, RotationalSpeed.From, out quantity), + // Type _ when quantityType == typeof(RotationalStiffness) => parser.TryParse<RotationalStiffness, RotationalStiffnessUnit>(quantityString, formatProvider, RotationalStiffness.From, out quantity), + // Type _ when quantityType == typeof(RotationalStiffnessPerLength) => parser.TryParse<RotationalStiffnessPerLength, RotationalStiffnessPerLengthUnit>(quantityString, formatProvider, RotationalStiffnessPerLength.From, out quantity), + // Type _ when quantityType == typeof(Scalar) => parser.TryParse<Scalar, ScalarUnit>(quantityString, formatProvider, Scalar.From, out quantity), + // Type _ when quantityType == typeof(SolidAngle) => parser.TryParse<SolidAngle, SolidAngleUnit>(quantityString, formatProvider, SolidAngle.From, out quantity), + // Type _ when quantityType == typeof(SpecificEnergy) => parser.TryParse<SpecificEnergy, SpecificEnergyUnit>(quantityString, formatProvider, SpecificEnergy.From, out quantity), + // Type _ when quantityType == typeof(SpecificEntropy) => parser.TryParse<SpecificEntropy, SpecificEntropyUnit>(quantityString, formatProvider, SpecificEntropy.From, out quantity), + // Type _ when quantityType == typeof(SpecificFuelConsumption) => parser.TryParse<SpecificFuelConsumption, SpecificFuelConsumptionUnit>(quantityString, formatProvider, SpecificFuelConsumption.From, out quantity), + // Type _ when quantityType == typeof(SpecificVolume) => parser.TryParse<SpecificVolume, SpecificVolumeUnit>(quantityString, formatProvider, SpecificVolume.From, out quantity), + // Type _ when quantityType == typeof(SpecificWeight) => parser.TryParse<SpecificWeight, SpecificWeightUnit>(quantityString, formatProvider, SpecificWeight.From, out quantity), + // Type _ when quantityType == typeof(Speed) => parser.TryParse<Speed, SpeedUnit>(quantityString, formatProvider, Speed.From, out quantity), + // Type _ when quantityType == typeof(StandardVolumeFlow) => parser.TryParse<StandardVolumeFlow, StandardVolumeFlowUnit>(quantityString, formatProvider, StandardVolumeFlow.From, out quantity), + // Type _ when quantityType == typeof(Temperature) => parser.TryParse<Temperature, TemperatureUnit>(quantityString, formatProvider, Temperature.From, out quantity), + // Type _ when quantityType == typeof(TemperatureChangeRate) => parser.TryParse<TemperatureChangeRate, TemperatureChangeRateUnit>(quantityString, formatProvider, TemperatureChangeRate.From, out quantity), + // Type _ when quantityType == typeof(TemperatureDelta) => parser.TryParse<TemperatureDelta, TemperatureDeltaUnit>(quantityString, formatProvider, TemperatureDelta.From, out quantity), + // Type _ when quantityType == typeof(TemperatureGradient) => parser.TryParse<TemperatureGradient, TemperatureGradientUnit>(quantityString, formatProvider, TemperatureGradient.From, out quantity), + // Type _ when quantityType == typeof(ThermalConductivity) => parser.TryParse<ThermalConductivity, ThermalConductivityUnit>(quantityString, formatProvider, ThermalConductivity.From, out quantity), + // Type _ when quantityType == typeof(ThermalResistance) => parser.TryParse<ThermalResistance, ThermalResistanceUnit>(quantityString, formatProvider, ThermalResistance.From, out quantity), + // Type _ when quantityType == typeof(Torque) => parser.TryParse<Torque, TorqueUnit>(quantityString, formatProvider, Torque.From, out quantity), + // Type _ when quantityType == typeof(TorquePerLength) => parser.TryParse<TorquePerLength, TorquePerLengthUnit>(quantityString, formatProvider, TorquePerLength.From, out quantity), + // Type _ when quantityType == typeof(Turbidity) => parser.TryParse<Turbidity, TurbidityUnit>(quantityString, formatProvider, Turbidity.From, out quantity), + // Type _ when quantityType == typeof(VitaminA) => parser.TryParse<VitaminA, VitaminAUnit>(quantityString, formatProvider, VitaminA.From, out quantity), + // Type _ when quantityType == typeof(Volume) => parser.TryParse<Volume, VolumeUnit>(quantityString, formatProvider, Volume.From, out quantity), + // Type _ when quantityType == typeof(VolumeConcentration) => parser.TryParse<VolumeConcentration, VolumeConcentrationUnit>(quantityString, formatProvider, VolumeConcentration.From, out quantity), + // Type _ when quantityType == typeof(VolumeFlow) => parser.TryParse<VolumeFlow, VolumeFlowUnit>(quantityString, formatProvider, VolumeFlow.From, out quantity), + // Type _ when quantityType == typeof(VolumeFlowPerArea) => parser.TryParse<VolumeFlowPerArea, VolumeFlowPerAreaUnit>(quantityString, formatProvider, VolumeFlowPerArea.From, out quantity), + // Type _ when quantityType == typeof(VolumePerLength) => parser.TryParse<VolumePerLength, VolumePerLengthUnit>(quantityString, formatProvider, VolumePerLength.From, out quantity), + // Type _ when quantityType == typeof(VolumetricHeatCapacity) => parser.TryParse<VolumetricHeatCapacity, VolumetricHeatCapacityUnit>(quantityString, formatProvider, VolumetricHeatCapacity.From, out quantity), + // Type _ when quantityType == typeof(WarpingMomentOfInertia) => parser.TryParse<WarpingMomentOfInertia, WarpingMomentOfInertiaUnit>(quantityString, formatProvider, WarpingMomentOfInertia.From, out quantity), + // _ => false + // }; + // } + // + // internal static IEnumerable<Type> GetQuantityTypes() + // { + // yield return typeof(Acceleration); + // yield return typeof(AmountOfSubstance); + // yield return typeof(AmplitudeRatio); + // yield return typeof(Angle); + // yield return typeof(ApparentEnergy); + // yield return typeof(ApparentPower); + // yield return typeof(Area); + // yield return typeof(AreaDensity); + // yield return typeof(AreaMomentOfInertia); + // yield return typeof(BitRate); + // yield return typeof(BrakeSpecificFuelConsumption); + // yield return typeof(Capacitance); + // yield return typeof(CoefficientOfThermalExpansion); + // yield return typeof(Compressibility); + // yield return typeof(Density); + // yield return typeof(Duration); + // yield return typeof(DynamicViscosity); + // yield return typeof(ElectricAdmittance); + // yield return typeof(ElectricCharge); + // yield return typeof(ElectricChargeDensity); + // yield return typeof(ElectricConductance); + // yield return typeof(ElectricConductivity); + // yield return typeof(ElectricCurrent); + // yield return typeof(ElectricCurrentDensity); + // yield return typeof(ElectricCurrentGradient); + // yield return typeof(ElectricField); + // yield return typeof(ElectricInductance); + // yield return typeof(ElectricPotential); + // yield return typeof(ElectricPotentialAc); + // yield return typeof(ElectricPotentialChangeRate); + // yield return typeof(ElectricPotentialDc); + // yield return typeof(ElectricResistance); + // yield return typeof(ElectricResistivity); + // yield return typeof(ElectricSurfaceChargeDensity); + // yield return typeof(Energy); + // yield return typeof(EnergyDensity); + // yield return typeof(Entropy); + // yield return typeof(Force); + // yield return typeof(ForceChangeRate); + // yield return typeof(ForcePerLength); + // yield return typeof(Frequency); + // yield return typeof(FuelEfficiency); + // yield return typeof(HeatFlux); + // yield return typeof(HeatTransferCoefficient); + // yield return typeof(Illuminance); + // yield return typeof(Information); + // yield return typeof(Irradiance); + // yield return typeof(Irradiation); + // yield return typeof(Jerk); + // yield return typeof(KinematicViscosity); + // yield return typeof(Length); + // yield return typeof(Level); + // yield return typeof(LinearDensity); + // yield return typeof(LinearPowerDensity); + // yield return typeof(Luminance); + // yield return typeof(Luminosity); + // yield return typeof(LuminousFlux); + // yield return typeof(LuminousIntensity); + // yield return typeof(MagneticField); + // yield return typeof(MagneticFlux); + // yield return typeof(Magnetization); + // yield return typeof(Mass); + // yield return typeof(MassConcentration); + // yield return typeof(MassFlow); + // yield return typeof(MassFlux); + // yield return typeof(MassFraction); + // yield return typeof(MassMomentOfInertia); + // yield return typeof(MolarEnergy); + // yield return typeof(MolarEntropy); + // yield return typeof(Molarity); + // yield return typeof(MolarMass); + // yield return typeof(Permeability); + // yield return typeof(Permittivity); + // yield return typeof(PorousMediumPermeability); + // yield return typeof(Power); + // yield return typeof(PowerDensity); + // yield return typeof(PowerRatio); + // yield return typeof(Pressure); + // yield return typeof(PressureChangeRate); + // yield return typeof(Ratio); + // yield return typeof(RatioChangeRate); + // yield return typeof(ReactiveEnergy); + // yield return typeof(ReactivePower); + // yield return typeof(ReciprocalArea); + // yield return typeof(ReciprocalLength); + // yield return typeof(RelativeHumidity); + // yield return typeof(RotationalAcceleration); + // yield return typeof(RotationalSpeed); + // yield return typeof(RotationalStiffness); + // yield return typeof(RotationalStiffnessPerLength); + // yield return typeof(Scalar); + // yield return typeof(SolidAngle); + // yield return typeof(SpecificEnergy); + // yield return typeof(SpecificEntropy); + // yield return typeof(SpecificFuelConsumption); + // yield return typeof(SpecificVolume); + // yield return typeof(SpecificWeight); + // yield return typeof(Speed); + // yield return typeof(StandardVolumeFlow); + // yield return typeof(Temperature); + // yield return typeof(TemperatureChangeRate); + // yield return typeof(TemperatureDelta); + // yield return typeof(TemperatureGradient); + // yield return typeof(ThermalConductivity); + // yield return typeof(ThermalResistance); + // yield return typeof(Torque); + // yield return typeof(TorquePerLength); + // yield return typeof(Turbidity); + // yield return typeof(VitaminA); + // yield return typeof(Volume); + // yield return typeof(VolumeConcentration); + // yield return typeof(VolumeFlow); + // yield return typeof(VolumeFlowPerArea); + // yield return typeof(VolumePerLength); + // yield return typeof(VolumetricHeatCapacity); + // yield return typeof(WarpingMomentOfInertia); + // } + } +} diff --git a/UnitsNet.Core/GenericMath/DecimalGenericMathExtensions.cs b/UnitsNet.Core/GenericMath/DecimalGenericMathExtensions.cs new file mode 100644 index 0000000000..2c686c9d90 --- /dev/null +++ b/UnitsNet.Core/GenericMath/DecimalGenericMathExtensions.cs @@ -0,0 +1,50 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +#if NET7_0_OR_GREATER + +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace UnitsNet.GenericMath; + +/// <summary> +/// Provides generic math operations to test out the new generic math interfaces implemented in .NET7 for UnitsNet +/// quantities using <see cref="decimal" /> as the internal value type, such as <see cref="Power" />, <see cref="BitRate" /> and +/// <see cref="Information" />. +/// </summary> +/// <remarks> +/// See <see cref="GenericMathExtensions" /> for quantities using <see cref="double" /> as the internal value type. +/// </remarks> +public static class DecimalGenericMathExtensions +{ + /// <summary> + /// Returns the average of values. + /// </summary> + /// <remarks> + /// This method is experimental and intended to test out the new generic math interfaces implemented in .NET7 for + /// UnitsNet quantities.<br /> + /// Generic math interfaces might replace <see cref="UnitMath" />.<br /> + /// Generic math LINQ support is still missing in the BCL, but is being worked on: + /// <a href="https://github.com/dotnet/runtime/issues/64031"> + /// API Proposal: Generic LINQ Numeric Operators · Issue + /// #64031 · dotnet/runtime + /// </a> + /// </remarks> + /// <param name="source">The values.</param> + /// <typeparam name="T">The value type.</typeparam> + /// <returns>The average.</returns> + public static T Average<T>(this IEnumerable<T> source) + where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>, IDivisionOperators<T, decimal, T> + { + // Put accumulator on right hand side of the addition operator to construct quantities with the same unit as the values. + // The addition operator implementation picks the unit from the left hand side, and the additive identity (e.g. Length.Zero) is always the base unit. + (T value, int count) result = source.Aggregate( + (value: T.AdditiveIdentity, count: 0), + (acc, item) => (value: item + acc.value, count: acc.count + 1)); + + return result.value / result.count; + } +} +#endif diff --git a/UnitsNet.Core/GenericMath/GenericMathExtensions.cs b/UnitsNet.Core/GenericMath/GenericMathExtensions.cs new file mode 100644 index 0000000000..c9b46844ce --- /dev/null +++ b/UnitsNet.Core/GenericMath/GenericMathExtensions.cs @@ -0,0 +1,72 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +#if NET7_0_OR_GREATER +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace UnitsNet.GenericMath; + +/// <summary> +/// Provides generic math operations to test out the new generic math interfaces implemented in .NET7 for UnitsNet +/// quantities using <see cref="double" /> as the internal value type, which is the majority of quantities. +/// </summary> +/// <remarks> +/// See <see cref="DecimalGenericMathExtensions" /> for quantities using <see cref="decimal" /> as the internal value +/// type. +/// </remarks> +public static class GenericMathExtensions +{ + /// <summary> + /// Returns the sum of values. + /// </summary> + /// <remarks> + /// This method is experimental and intended to test out the new generic math interfaces implemented in .NET7 for + /// UnitsNet quantities.<br /> + /// Generic math interfaces might replace <see cref="UnitMath" />.<br /> + /// Generic math LINQ support is still missing in the BCL, but is being worked on: + /// <a href="https://github.com/dotnet/runtime/issues/64031"> + /// API Proposal: Generic LINQ Numeric Operators · Issue #64031 · dotnet/runtime + /// </a> + /// </remarks> + /// <param name="source">The values.</param> + /// <typeparam name="T">The type of value.</typeparam> + /// <returns>The sum.</returns> + public static T Sum<T>(this IEnumerable<T> source) + where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T> + { + // Put accumulator on right hand side of the addition operator to construct quantities with the same unit as the values. + // The addition operator implementation picks the unit from the left hand side, and the additive identity (e.g. Length.Zero) is always the base unit. + return source.Aggregate(T.AdditiveIdentity, (acc, item) => item + acc); + } + + /// <summary> + /// Returns the average of values. + /// </summary> + /// <remarks> + /// This method is experimental and intended to test out the new generic math interfaces implemented in .NET7 for + /// UnitsNet quantities.<br /> + /// Generic math interfaces might replace <see cref="UnitMath" />.<br /> + /// Generic math LINQ support is still missing in the BCL, but is being worked on: + /// <a href="https://github.com/dotnet/runtime/issues/64031"> + /// API Proposal: Generic LINQ Numeric Operators · Issue + /// #64031 · dotnet/runtime + /// </a> + /// </remarks> + /// <param name="source">The values.</param> + /// <typeparam name="T">The value type.</typeparam> + /// <returns>The average.</returns> + public static T Average<T>(this IEnumerable<T> source) + where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>, IDivisionOperators<T, double, T> + { + // Put accumulator on right hand side of the addition operator to construct quantities with the same unit as the values. + // The addition operator implementation picks the unit from the left hand side, and the additive identity (e.g. Length.Zero) is always the base unit. + (T value, int count) result = source.Aggregate( + (value: T.AdditiveIdentity, count: 0), + (acc, item) => (value: item + acc.value, count: acc.count + 1)); + + return result.value / result.count; + } +} +#endif diff --git a/UnitsNet.Core/IArithmeticQuantity.cs b/UnitsNet.Core/IArithmeticQuantity.cs new file mode 100644 index 0000000000..1e60697fa8 --- /dev/null +++ b/UnitsNet.Core/IArithmeticQuantity.cs @@ -0,0 +1,31 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Numerics; + +namespace UnitsNet; + +/// <summary> +/// An <see cref="IQuantity{TSelf, TUnitType, TValueType}"/> that (in .NET 7+) implements generic math interfaces for arithmetic operations. +/// </summary> +/// <typeparam name="TSelf">The type itself, for the CRT pattern.</typeparam> +/// <typeparam name="TUnitType">The underlying unit enum type.</typeparam> +/// <typeparam name="TValueType">The underlying value type for internal representation.</typeparam> +public interface IArithmeticQuantity<TSelf, TUnitType, TValueType> : IQuantity<TSelf, TUnitType, TValueType> +#if NET7_0_OR_GREATER + , IAdditionOperators<TSelf, TSelf, TSelf> + , IAdditiveIdentity<TSelf, TSelf> + , ISubtractionOperators<TSelf, TSelf, TSelf> + , IMultiplyOperators<TSelf, TValueType, TSelf> + , IDivisionOperators<TSelf, TValueType, TSelf> + , IUnaryNegationOperators<TSelf, TSelf> +#endif + where TSelf : IArithmeticQuantity<TSelf, TUnitType, TValueType> + where TUnitType : Enum + where TValueType : struct +#if NET7_0_OR_GREATER + , INumber<TValueType> +#endif +{ +} diff --git a/UnitsNet.Core/IDecimalQuantity.cs b/UnitsNet.Core/IDecimalQuantity.cs new file mode 100644 index 0000000000..41ccd7787f --- /dev/null +++ b/UnitsNet.Core/IDecimalQuantity.cs @@ -0,0 +1,16 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +namespace UnitsNet +{ + /// <summary> + /// Represents a quantity with a decimal value. + /// </summary> + public interface IDecimalQuantity + { + /// <summary> + /// The decimal value this quantity was constructed with. + /// </summary> + decimal Value { get; } + } +} diff --git a/UnitsNet.Core/IQuantity.cs b/UnitsNet.Core/IQuantity.cs new file mode 100644 index 0000000000..af64536e54 --- /dev/null +++ b/UnitsNet.Core/IQuantity.cs @@ -0,0 +1,148 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Globalization; +#if NET7_0_OR_GREATER +using System.Numerics; +#endif + +namespace UnitsNet +{ + /// <summary> + /// Represents a quantity. + /// </summary> + public interface IQuantity : IFormattable + { +#if NET7_0_OR_GREATER + /// <summary> + /// The zero value of this quantity. + /// </summary> + static abstract QuantityInfo Info { get; } +#endif + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + BaseDimensions Dimensions { get; } + + /// <summary> + /// Information about the quantity type, such as unit values and names. + /// </summary> + QuantityInfo QuantityInfo { get; } + + /// <summary> + /// Gets the value in the given unit. + /// </summary> + /// <param name="unit">The unit enum value. The unit must be compatible, so for <see cref="Length"/> you should provide a <see cref="LengthUnit"/> value.</param> + /// <returns>Value converted to the specified unit.</returns> + /// <exception cref="InvalidCastException">Wrong unit enum type was given.</exception> + double As(Enum unit); + + // /// <summary> + // /// Gets the value in the unit determined by the given <see cref="UnitSystem"/>. If multiple units were found for the given <see cref="UnitSystem"/>, + // /// the first match will be used. + // /// </summary> + // /// <param name="unitSystem">The <see cref="UnitSystem"/> to convert the quantity value to.</param> + // /// <returns>The converted value.</returns> + // double As(UnitSystem unitSystem); + + /// <summary> + /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. + /// </summary> + Enum Unit { get; } + + /// <summary> + /// The value this quantity was constructed with. See also <see cref="Unit"/>. + /// </summary> + QuantityValue Value { get; } + + /// <summary> + /// Converts this <see cref="IQuantity"/> to an <see cref="IQuantity"/> in the given <paramref name="unit"/>. + /// </summary> + /// <param name="unit"> + /// The unit <see cref="Enum"/> value. The <see cref="Enum"/> must be compatible with the units of the <see cref="IQuantity"/>. + /// For example, if the <see cref="IQuantity"/> is a <see cref="Length"/>, you should provide a <see cref="LengthUnit"/> value. + /// </param> + /// <exception cref="NotImplementedException">Conversion was not possible from this <see cref="IQuantity"/> to <paramref name="unit"/>.</exception> + /// <returns>A new <see cref="IQuantity"/> in the given <paramref name="unit"/>.</returns> + IQuantity ToUnit(Enum unit); + + // /// <summary> + // /// Converts to a quantity with a unit determined by the given <see cref="UnitSystem"/>, which affects things like <see cref="IQuantity.ToString(System.IFormatProvider)"/>. + // /// If multiple units were found for the given <see cref="UnitSystem"/>, the first match will be used. + // /// </summary> + // /// <param name="unitSystem">The <see cref="UnitSystem"/> to convert the quantity to.</param> + // /// <returns>A new quantity with the determined unit.</returns> + // IQuantity ToUnit(UnitSystem unitSystem); + + /// <summary> + /// Gets the string representation of value and unit. Uses two significant digits after radix. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + string ToString(IFormatProvider? provider); + } + + /// <summary> + /// A stronger typed interface where the unit enum type is known, to avoid passing in the + /// wrong unit enum type and not having to cast from <see cref="Enum"/>. + /// </summary> + /// <example> + /// IQuantity{LengthUnit} length; + /// double centimeters = length.As(LengthUnit.Centimeter); // Type safety on enum type + /// </example> + public interface IQuantity<TUnitType> : IQuantity where TUnitType : Enum + { + /// <summary> + /// Convert to a unit representation <typeparamref name="TUnitType"/>. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + double As(TUnitType unit); + + /// <inheritdoc cref="IQuantity.Unit"/> + new TUnitType Unit { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + new QuantityInfo<TUnitType> QuantityInfo { get; } + + /// <summary> + /// Converts this <see cref="IQuantity{TUnitType}"/> to an <see cref="IQuantity{TUnitType}"/> in the given <paramref name="unit"/>. + /// </summary> + /// <param name="unit">The unit value.</param> + /// <exception cref="NotImplementedException">Conversion was not possible from this <see cref="IQuantity"/> to <paramref name="unit"/>.</exception> + /// <returns>A new <see cref="IQuantity{TUnitType}"/> in the given <paramref name="unit"/>.</returns> + IQuantity<TUnitType> ToUnit(TUnitType unit); + + // /// <summary> + // /// Converts to a quantity with a unit determined by the given <see cref="UnitSystem"/>, which affects things like <see cref="IQuantity.ToString(System.IFormatProvider)"/>. + // /// If multiple units were found for the given <see cref="UnitSystem"/>, the first match will be used. + // /// </summary> + // /// <param name="unitSystem">The <see cref="UnitSystem"/> to convert the quantity to.</param> + // /// <returns>A new quantity with the determined unit.</returns> + // new IQuantity<TUnitType> ToUnit(UnitSystem unitSystem); + } + + /// <summary> + /// An <see cref="IQuantity{TUnitType}"/> that (in .NET 7+) implements generic math interfaces for equality, comparison and parsing. + /// </summary> + /// <typeparam name="TSelf">The type itself, for the CRT pattern.</typeparam> + /// <typeparam name="TUnitType">The underlying unit enum type.</typeparam> + /// <typeparam name="TValueType">The underlying value type for internal representation.</typeparam> + public interface IQuantity<TSelf, TUnitType, TValueType> : IQuantity<TUnitType> +#if NET7_0_OR_GREATER + , IComparisonOperators<TSelf, TSelf, bool> + , IParsable<TSelf> +#endif + where TSelf : IQuantity<TSelf, TUnitType, TValueType> + where TUnitType : Enum + where TValueType : struct + { +#if NET7_0_OR_GREATER + /// <summary> + /// The zero value of this quantity. + /// </summary> + static abstract TSelf Zero { get; } +#endif + } +} diff --git a/UnitsNet.Core/InternalHelpers/BytesUtility.cs b/UnitsNet.Core/InternalHelpers/BytesUtility.cs new file mode 100644 index 0000000000..e75e467773 --- /dev/null +++ b/UnitsNet.Core/InternalHelpers/BytesUtility.cs @@ -0,0 +1,40 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Runtime.InteropServices; + +namespace UnitsNet.InternalHelpers +{ + /// <summary> + /// Utility methods for working with the byte representation of structs. + /// </summary> + internal static class BytesUtility + { + /// <summary> + /// Converts the given <paramref name="value"/> to an array of its underlying bytes. + /// </summary> + /// <typeparam name="T">The struct type.</typeparam> + /// <param name="value">The struct value to convert.</param> + /// <returns>A byte array representing a copy of <paramref name="value"/>s bytes.</returns> + internal static byte[] GetBytes<T>(T value) where T : struct + { + int size = Marshal.SizeOf(value); + byte[] array = new byte[size]; + + IntPtr ptr = Marshal.AllocHGlobal(size); + + try + { + Marshal.StructureToPtr(value, ptr, true); + Marshal.Copy(ptr, array, 0, size); + } + finally + { + Marshal.FreeHGlobal(ptr); + } + + return array; + } + } +} diff --git a/UnitsNet.Core/InternalHelpers/Guard.cs b/UnitsNet.Core/InternalHelpers/Guard.cs new file mode 100644 index 0000000000..c43210d088 --- /dev/null +++ b/UnitsNet.Core/InternalHelpers/Guard.cs @@ -0,0 +1,28 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +namespace UnitsNet.InternalHelpers +{ + /// <summary> + /// Guard methods to ensure parameter values satisfy pre-conditions and use a consistent exception message. + /// </summary> + internal static class Guard + { + /// <summary> + /// Throws <see cref="ArgumentException" /> if value is <see cref="double.NaN" />, + /// <see cref="double.PositiveInfinity" /> or <see cref="double.NegativeInfinity" />. + /// </summary> + /// <param name="value">The value to check.</param> + /// <param name="paramName">Name of parameter in calling method.</param> + /// <returns>The given <paramref name="value" /> if valid.</returns> + /// <exception cref="ArgumentException">If <paramref name="value" /> is invalid.</exception> + internal static double EnsureValidNumber(double value, string paramName) + { + if (double.IsNaN(value)) throw new ArgumentException("NaN is not a valid number.", paramName); + if (double.IsInfinity(value)) throw new ArgumentException("PositiveInfinity or NegativeInfinity is not a valid number.", paramName); + return value; + } + } +} diff --git a/UnitsNet.Core/QuantityFormatter.cs b/UnitsNet.Core/QuantityFormatter.cs new file mode 100644 index 0000000000..b268c96e57 --- /dev/null +++ b/UnitsNet.Core/QuantityFormatter.cs @@ -0,0 +1,189 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Globalization; +using System.Linq; + +namespace UnitsNet +{ + /// <summary> + /// The QuantityFormatter class is responsible for formatting a quantity using the given format string. + /// </summary> + public class QuantityFormatter + { + /// <summary> + /// The available UnitsNet custom format specifiers. + /// </summary> + private static readonly char[] UnitsNetFormatSpecifiers = { 'A', 'a', 'G', 'g', 'Q', 'q', 'S', 's', 'U', 'u', 'V', 'v' }; + + /// <summary> + /// Formats a quantity using the given format string and format provider. + /// </summary> + /// <typeparam name="TUnitType">The quantity's unit type, for example <see cref="LengthUnit"/>.</typeparam> + /// <param name="quantity">The quantity to format.</param> + /// <param name="format">The format string.</param> + /// <remarks> + /// The valid format strings are as follows: + /// <list type="bullet"> + /// <item> + /// <term>A standard numeric format string.</term> + /// <description>Any of the standard numeric format for <see cref="IQuantity.Value" />, except for "G" or "g", which have a special implementation. + /// "C" or "c", "E" or "e", "F" or "f", "N" or "n", "P" or "p", "R" or "r" are all accepted. + /// See https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#standard-format-specifiers. + /// </description> + /// </item> + /// <item> + /// <term>"G" or "g".</term> + /// <description>The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m".</description> + /// </item> + /// <item> + /// <term>"A" or "a".</term> + /// <description>The default unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />, such as "m".</description> + /// </item> + /// <item> + /// <term>"A0", "A1", ..., "An" or "a0", "a1", ..., "an".</term> + /// <description>The n-th unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />. "a0" is the same as "a". + /// A <see cref="FormatException"/> will be thrown if the requested abbreviation index does not exist.</description> + /// </item> + /// <item> + /// <term>"U" or "u".</term> + /// <description>The enum name of <see cref="IQuantity{TUnitType}.Unit" />, such as "Meter".</description> + /// </item> + /// <item> + /// <term>"Q" or "q".</term> + /// <description>The quantity name, such as "Length".</description> + /// </item> + /// </list> + /// </remarks> + /// <returns>The string representation.</returns> + public static string Format<TUnitType>(IQuantity<TUnitType> quantity, string format) + where TUnitType : Enum + { + return Format(quantity, format, CultureInfo.CurrentCulture); + } + + /// <summary> + /// Formats a quantity using the given format string and format provider. + /// </summary> + /// <typeparam name="TUnitType">The quantity's unit type, for example <see cref="LengthUnit"/>.</typeparam> + /// <param name="quantity">The quantity to format.</param> + /// <param name="format">The format string.</param> + /// <param name="formatProvider">The format provider to use for localization and number formatting. Defaults to + /// <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <remarks> + /// The valid format strings are as follows: + /// <list type="bullet"> + /// <item> + /// <term>A standard numeric format string.</term> + /// <description>Any of the standard numeric format for <see cref="IQuantity.Value" />, except for "G" or "g", which have a special implementation. + /// "C" or "c", "E" or "e", "F" or "f", "N" or "n", "P" or "p", "R" or "r" are all accepted. + /// See https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#standard-format-specifiers. + /// </description> + /// </item> + /// <item> + /// <term>"G" or "g".</term> + /// <description>The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m".</description> + /// </item> + /// <item> + /// <term>"A" or "a".</term> + /// <description>The default unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />, such as "m".</description> + /// </item> + /// <item> + /// <term>"A0", "A1", ..., "An" or "a0", "a1", ..., "an".</term> + /// <description>The n-th unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />. "a0" is the same as "a". + /// A <see cref="FormatException"/> will be thrown if the requested abbreviation index does not exist.</description> + /// </item> + /// <item> + /// <term>"U" or "u".</term> + /// <description>The enum name of <see cref="IQuantity{TUnitType}.Unit" />, such as "Meter".</description> + /// </item> + /// <item> + /// <term>"Q" or "q".</term> + /// <description>The quantity name, such as "Length".</description> + /// </item> + /// </list> + /// </remarks> + /// <returns>The string representation.</returns> + public static string Format<TUnitType>(IQuantity<TUnitType> quantity, string? format, IFormatProvider? formatProvider) + where TUnitType : Enum + { + formatProvider ??= CultureInfo.CurrentCulture; + return FormatUntrimmed(quantity, format, formatProvider).TrimEnd(); + } + + private static string FormatUntrimmed<TUnitType>(IQuantity<TUnitType> quantity, string? format, IFormatProvider? formatProvider) + where TUnitType : Enum + { + formatProvider ??= CultureInfo.CurrentCulture; + + if (string.IsNullOrWhiteSpace(format)) + format = "g"; + + char formatSpecifier = format![0]; // netstandard2.0 nullable quirk + + if (UnitsNetFormatSpecifiers.Any(unitsNetFormatSpecifier => unitsNetFormatSpecifier == formatSpecifier)) + { + // UnitsNet custom format string + + int precisionSpecifier = 0; + + switch(formatSpecifier) + { + case 'A': + case 'a': + case 'S': + case 's': + if (format.Length > 1 && !int.TryParse(format.Substring(1), out precisionSpecifier)) + throw new FormatException($"The {format} format string is not supported."); + break; + } + + switch(formatSpecifier) + { + case 'G': + case 'g': + return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, 2); + case 'A': + case 'a': + var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider); + + if (precisionSpecifier >= abbreviations.Length) + throw new FormatException($"The {format} format string is invalid because the abbreviation index does not exist."); + + return abbreviations[precisionSpecifier]; + case 'V': + case 'v': + return quantity.Value.ToString(formatProvider); + case 'U': + case 'u': + return quantity.Unit.ToString(); + case 'Q': + case 'q': + return quantity.QuantityInfo.Name; + case 'S': + case 's': + return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, precisionSpecifier); + default: + throw new FormatException($"The {format} format string is not supported."); + } + } + else + { + // Anything else is a standard numeric format string with default unit abbreviation postfix. + + var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider); + return string.Format(formatProvider, $"{{0:{format}}} {{1}}", quantity.Value, abbreviations.First()); + } + } + + private static string ToStringWithSignificantDigitsAfterRadix<TUnitType>(IQuantity<TUnitType> quantity, IFormatProvider formatProvider, int number) where TUnitType : Enum + { + // When a fixed number of digits after the dot is expected, double and decimal behave the same. + var value = (double)quantity.Value; + string formatForSignificantDigits = UnitFormatter.GetFormat(value, number); + object[] formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, value, formatProvider, Enumerable.Empty<object>()); + return string.Format(formatProvider, formatForSignificantDigits, formatArgs); + } + } +} diff --git a/UnitsNet.Core/QuantityInfo.cs b/UnitsNet.Core/QuantityInfo.cs new file mode 100644 index 0000000000..f74d4b4827 --- /dev/null +++ b/UnitsNet.Core/QuantityInfo.cs @@ -0,0 +1,203 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; + +namespace UnitsNet +{ + /// <summary> + /// Delegate to construct a quantity from a value and unit. + /// </summary> + public delegate IQuantity QuantityFactory(QuantityValue value, Enum unit); + + /// <summary> + /// Information about the quantity, such as names, unit values and zero quantity. + /// This is useful to enumerate units and present names with quantities and units + /// chose dynamically at runtime, such as unit conversion apps or allowing the user to change the + /// unit representation. + /// </summary> + /// <remarks> + /// Typically you obtain this by looking it up via <see cref="IQuantity.QuantityInfo" />. + /// </remarks> + public class QuantityInfo + { + private readonly QuantityFactory _quantityFactory; + + /// <summary> + /// Constructs an instance. + /// </summary> + /// <param name="name">Name of the quantity.</param> + /// <param name="unitType">The unit enum type, such as <see cref="LengthUnit" />.</param> + /// <param name="unitInfos">The information about the units for this quantity.</param> + /// <param name="baseUnit">The base unit enum value.</param> + /// <param name="zero">The zero quantity.</param> + /// <param name="baseDimensions">The base dimensions of the quantity.</param> + /// <param name="quantityFactory">The quantity factory.</param> + /// <exception cref="ArgumentException">Quantity type can not be undefined.</exception> + /// <exception cref="ArgumentNullException">If units -or- baseUnit -or- zero -or- baseDimensions is null.</exception> + public QuantityInfo(string name, Type unitType, UnitInfo[] unitInfos, Enum baseUnit, IQuantity zero, BaseDimensions baseDimensions, QuantityFactory quantityFactory) + { + if (baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); + BaseDimensions = baseDimensions ?? throw new ArgumentNullException(nameof(baseDimensions)); + _quantityFactory = quantityFactory ?? throw new ArgumentNullException(nameof(quantityFactory)); + Zero = zero ?? throw new ArgumentNullException(nameof(zero)); + Name = name ?? throw new ArgumentNullException(nameof(name)); + UnitType = unitType ?? throw new ArgumentNullException(nameof(unitType)); + UnitInfos = unitInfos ?? throw new ArgumentNullException(nameof(unitInfos)); + AbbreviationsForAllUnits = unitInfos.SelectMany(ui => ui.Abbreviations).ToArray(); + + BaseUnitInfo = UnitInfos.First(unitInfo => unitInfo.Value.Equals(baseUnit)); + ValueType = zero.GetType(); + } + + /// <summary> + /// Quantity name, such as "Length" or "Mass". + /// </summary> + public string Name { get; } + + /// <summary> + /// All unit abbreviations for all units of this quantity. + /// </summary> + public IReadOnlyList<string> AbbreviationsForAllUnits { get; } + + /// <summary> + /// The units for this quantity. + /// </summary> + public UnitInfo[] UnitInfos { get; } + + /// <summary> + /// The base unit of this quantity. + /// </summary> + public UnitInfo BaseUnitInfo { get; } + + /// <summary> + /// Zero value of quantity, such as <see cref="Length.Zero" />. + /// </summary> + public IQuantity Zero { get; } + + /// <summary> + /// Unit enum type, such as <see cref="LengthUnit"/> or <see cref="MassUnit"/>. + /// </summary> + public Type UnitType { get; } + + /// <summary> + /// Quantity value type, such as <see cref="Length"/> or <see cref="Mass"/>. + /// </summary> + public Type ValueType { get; } + + /// <summary> + /// The <see cref="BaseDimensions" /> for a quantity. + /// </summary> + public BaseDimensions BaseDimensions { get; } + + /// <summary> + /// Construct a quantity from a value and unit. + /// </summary> + public IQuantity CreateQuantity(QuantityValue value, Enum unit) + { + return _quantityFactory(value, unit); + } + + // /// <summary> + // /// Gets the <see cref="UnitInfo"/> whose <see cref="BaseUnits"/> is a subset of <paramref name="baseUnits"/>. + // /// </summary> + // /// <example>Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns <see cref="UnitInfo" /> for <see cref="LengthUnit.Foot" />.</example> + // /// <param name="baseUnits">The <see cref="BaseUnits"/> to check against.</param> + // /// <returns>The <see cref="UnitInfo"/> that has <see cref="BaseUnits"/> that is a subset of <paramref name="baseUnits"/>.</returns> + // /// <exception cref="ArgumentNullException"><paramref name="baseUnits"/> is null.</exception> + // /// <exception cref="InvalidOperationException">No unit was found that is a subset of <paramref name="baseUnits"/>.</exception> + // /// <exception cref="InvalidOperationException">More than one unit was found that is a subset of <paramref name="baseUnits"/>.</exception> + // public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) + // { + // if (baseUnits is null) + // throw new ArgumentNullException(nameof(baseUnits)); + // + // var matchingUnitInfos = GetUnitInfosFor(baseUnits) + // .Take(2) + // .ToArray(); + // + // var firstUnitInfo = matchingUnitInfos.FirstOrDefault(); + // if (firstUnitInfo == null) + // throw new InvalidOperationException($"No unit was found that is a subset of {nameof(baseUnits)}"); + // + // if (matchingUnitInfos.Length > 1) + // throw new InvalidOperationException($"More than one unit was found that is a subset of {nameof(baseUnits)}"); + // + // return firstUnitInfo; + // } + // + // /// <summary> + // /// Gets an <see cref="IEnumerable{T}"/> of <see cref="UnitInfo"/> that have <see cref="BaseUnits"/> that is a subset of <paramref name="baseUnits"/>. + // /// </summary> + // /// <param name="baseUnits">The <see cref="BaseUnits"/> to check against.</param> + // /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="UnitInfo"/> that have <see cref="BaseUnits"/> that is a subset of <paramref name="baseUnits"/>.</returns> + // /// <exception cref="ArgumentNullException"><paramref name="baseUnits"/> is null.</exception> + // public IEnumerable<UnitInfo> GetUnitInfosFor(BaseUnits baseUnits) + // { + // if (baseUnits is null) + // throw new ArgumentNullException(nameof(baseUnits)); + // + // return UnitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); + // } + + /// <summary> + /// Try to parse a quantity of type <see cref="ValueType"/> from a string. + /// </summary> + /// <param name="formatProvider">The format provider, for number formatting and localization of unit abbreviations.</param> + /// <param name="quantityString">The string to parse, such as "1.5 m".</param> + /// <param name="quantity">The parsed quantity, or null if not successful.</param> + /// <returns>True if successful.</returns> + public bool TryParse(IFormatProvider? formatProvider, string quantityString, [NotNullWhen(true)] out IQuantity? quantity) + { + return QuantityParser.Default.TryParse(quantityString, formatProvider, UnitType, AbbreviationsForAllUnits, CreateQuantity, out quantity); + } + } + + /// <inheritdoc cref="QuantityInfo" /> + /// <remarks> + /// This is a specialization of <see cref="QuantityInfo" />, for when the unit type is known. + /// Typically you obtain this by looking it up statically from <see cref="Length.Info" /> or + /// <see cref="Length.QuantityInfo" />, or dynamically via <see cref="IQuantity{TUnitType}.QuantityInfo" />. + /// </remarks> + /// <typeparam name="TUnit">The unit enum type, such as <see cref="LengthUnit" />. </typeparam> + public class QuantityInfo<TUnit> : QuantityInfo + where TUnit : Enum + { + /// <inheritdoc /> + public QuantityInfo(string name, UnitInfo<TUnit>[] unitInfos, TUnit baseUnit, IQuantity<TUnit> zero, BaseDimensions baseDimensions, QuantityFactory quantityFactory) + : base(name, typeof(TUnit), unitInfos.ToArray<UnitInfo>(), baseUnit, zero, baseDimensions, quantityFactory) + { + Zero = zero; + UnitInfos = unitInfos ?? throw new ArgumentNullException(nameof(unitInfos)); + BaseUnitInfo = UnitInfos.First(unitInfo => unitInfo.Value.Equals(baseUnit)); + UnitType = baseUnit; + } + + /// <inheritdoc cref="QuantityInfo.UnitInfos" /> + public new UnitInfo<TUnit>[] UnitInfos { get; } + + /// <inheritdoc cref="QuantityInfo.BaseUnitInfo" /> + public new UnitInfo<TUnit> BaseUnitInfo { get; } + + /// <inheritdoc cref="QuantityInfo.Zero" /> + public new IQuantity<TUnit> Zero { get; } + + /// <inheritdoc cref="QuantityInfo.UnitType" /> + public new TUnit UnitType { get; } + + // /// <inheritdoc cref="QuantityInfo.GetUnitInfoFor" /> + // public new UnitInfo<TUnit> GetUnitInfoFor(BaseUnits baseUnits) + // { + // return (UnitInfo<TUnit>)base.GetUnitInfoFor(baseUnits); + // } + // + // /// <inheritdoc cref="QuantityInfo.GetUnitInfosFor" /> + // public new IEnumerable<UnitInfo<TUnit>> GetUnitInfosFor(BaseUnits baseUnits) + // { + // return base.GetUnitInfosFor(baseUnits).Cast<UnitInfo<TUnit>>(); + // } + } +} diff --git a/UnitsNet.Core/QuantityTypeConverter.cs b/UnitsNet.Core/QuantityTypeConverter.cs new file mode 100644 index 0000000000..40f5b66d65 --- /dev/null +++ b/UnitsNet.Core/QuantityTypeConverter.cs @@ -0,0 +1,239 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.ComponentModel; +using System.Globalization; + +namespace UnitsNet +{ + /// <summary> + /// Is the base class for all attributes that are related to <see cref="QuantityTypeConverter{T}"/> + /// </summary> + [AttributeUsage(AttributeTargets.Property)] + public abstract class UnitAttributeBase : Attribute + { + /// <summary> + /// The unit to convert to, such as <see cref="UnitsNet.Units.LengthUnit" />. Defaults to the unit the quantity as constructed with. + /// </summary> + public Enum? UnitType { get; set; } + + /// <summary> + /// Initializes a new instance of the <see cref="UnitAttributeBase"/> class. + /// </summary> + /// <param name="unitType"></param> + public UnitAttributeBase(object? unitType) + { + UnitType = unitType as Enum; + } + } + + /// <summary> + /// This attribute defines the default Unit to use if the string to convert only consists of digits + /// </summary> + public class DefaultUnitAttribute : UnitAttributeBase + { + /// <summary> + /// Initializes a new instance of the <see cref="DefaultUnitAttribute"/> class. + /// </summary> + /// <param name="unitType">The unit the quantity gets when the string parsing dose only consist of digits</param> + public DefaultUnitAttribute(object? unitType) : base(unitType) { } + } + + /// <summary> + /// This attribute defines the Unit the quantity is converted to after it has been parsed. + /// </summary> + public class ConvertToUnitAttribute : DefaultUnitAttribute + { + /// <summary> + /// Initializes a new instance of the <see cref="ConvertToUnitAttribute"/> class. + /// </summary> + /// <param name="unitType">The unit the quantity is converted to when parsing from string</param> + public ConvertToUnitAttribute(object? unitType) : base(unitType) { } + } + + /// <summary> + /// This attribute defines the unit the quantity has when converting to string + /// </summary> + public class DisplayAsUnitAttribute : DefaultUnitAttribute + { + /// <summary> + /// The formatting used when the quantity is converted to string. See <see cref="IQuantity.ToString(System.IFormatProvider)"/> + /// </summary> + public string Format { get; set; } + + /// <summary> + /// Initializes a new instance of the <see cref="DisplayAsUnitAttribute"/> class. + /// </summary> + /// <param name="unitType">The unit the quantity should be displayed in</param> + /// <param name="format">Formatting string <see cref="IQuantity.ToString(System.IFormatProvider)"/> </param> + public DisplayAsUnitAttribute(object? unitType, string format = "") : base(unitType) + { + Format = format; + } + } + + /// <summary> + /// <para> + /// Converts between IQuantity and string. + /// Implements a TypeConverter for IQuantities. This allows eg the PropertyGrid to read and write properties of type IQuantity. + /// </para> + /// <para>For basic understanding of TypeConverters consult the .NET documentation.</para> + /// </summary> + /// <typeparam name="TQuantity">Quantity value type, such as <see cref="Length"/> or <see cref="Mass"/>.</typeparam> + /// <remarks> + /// <para> + /// When a string is converted a Quantity the unit given by the string is used. + /// When no unit is given by the string the base unit is used. + /// The base unit can be overwritten by use of the <see cref="DefaultUnitAttribute"/>. + /// The converted Quantity can be forced to be in a certain unit by use of the <see cref="ConvertToUnitAttribute"/>. + /// </para> + /// <para> + /// The displayed unit can be forced to a certain unit by use of the <see cref="DisplayAsUnitAttribute"/>. + /// The <see cref="DisplayAsUnitAttribute"/> provides the possibility to format the displayed Quantity. + /// </para> + /// </remarks> + /// <example> + /// <para>These examples show how to use this TypeConverter.</para> + /// + /// <code title="Using the TypeConverter without additional attributes"> + /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] + /// Units.Length PropertyName { get; set; } + /// </code> + /// + /// <code title="Using the TypeConverter with DisplayAsUnit attribute"> + /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter)] + /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] + /// Units.Length Length { get; set; } + /// </code> + /// + /// <code title="Using the TypeConverter with DisplayAsUnit attribute with formatting"> + /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter, "g")] + /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] + /// Units.Length Length { get; set; } + /// </code> + /// + /// <code title="Using the TypeConverter with ConvertToUnit attribute"> + /// [ConvertToUnitAttribute(UnitsNet.Units.LengthUnit.Meter)] + /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] + /// Units.Length Length { get; set; } + /// </code> + /// + /// <code title="Using the TypeConverter with DefaultUnit attribute"> + /// [DefaultUnitAttribute(UnitsNet.Units.LengthUnit.Meter)] + /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] + /// Units.Length Length { get; set; } + /// </code> + /// </example> + public class QuantityTypeConverter<TQuantity> : TypeConverter where TQuantity : struct, IQuantity + { + /// <summary> + /// Returns true if sourceType if of type <see cref="string"/> + /// </summary> + /// <param name="context">An <see cref="System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param> + /// <param name="sourceType">A <see cref="System.Type"/> that represents the type you want to convert from.</param> + /// <returns>true if this converter can perform the conversion; otherwise, false.</returns> + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) + { + return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType); + } + + private static TAttribute? GetAttribute<TAttribute>(ITypeDescriptorContext? context) where TAttribute : UnitAttributeBase + { + if (context?.PropertyDescriptor is null) return null; + + var attribute = (TAttribute?)context.PropertyDescriptor.Attributes[typeof(TAttribute)]; + + // Ensure the attribute's unit is compatible with this converter's quantity. + if (attribute?.UnitType != null) + { + string converterQuantityName = default(TQuantity).QuantityInfo.Name; + string attributeQuantityName = Quantity.From(1, attribute.UnitType).QuantityInfo.Name; + if (converterQuantityName != attributeQuantityName) + { + throw new ArgumentException($"The {attribute.GetType()}'s UnitType [{attribute.UnitType}] is not compatible with the converter's quantity [{converterQuantityName}]."); + } + } + + return attribute; + } + + /// <summary> + /// Converts the given object, when it is of type <see cref="string"/> to the type of this converter, using the specified context and culture information. + /// </summary> + /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param> + /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param> + /// <param name="value">The System.Object to convert.</param> + /// <returns>An <see cref="IQuantity"/> object.</returns> + /// <exception cref="System.NotSupportedException">The conversion cannot be performed.</exception> + /// <exception cref="ArgumentException">Unit value is not a know unit enum type.</exception> + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) + { + if (value is string stringValue && !string.IsNullOrEmpty(stringValue)) + { + IQuantity? quantity = null; + + if (double.TryParse(stringValue, NumberStyles.Any, culture, out double dvalue)) + { + var defaultUnit = GetAttribute<DefaultUnitAttribute>(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); + if(defaultUnit.UnitType != null) + quantity = Quantity.From(dvalue, defaultUnit.UnitType); + } + else + { + quantity = Quantity.Parse(culture, typeof(TQuantity), stringValue); + } + + if( quantity != null) + { + ConvertToUnitAttribute? convertToUnit = GetAttribute<ConvertToUnitAttribute>(context); + if (convertToUnit != null && convertToUnit.UnitType != null) + quantity = quantity.ToUnit(convertToUnit.UnitType); + + return quantity; + } + } + + return base.ConvertFrom(context, culture, value); + } + + /// <summary>Returns true whether this converter can convert the <see cref="IQuantity"/> to string, using the specified context.</summary> + /// <returns>true if this converter can perform the conversion; otherwise, false.</returns> + /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context. </param> + /// <param name="destinationType">A <see cref="T:System.Type" /> that represents the type you want to convert to. </param> + public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) + { + return (destinationType == typeof(string)) || base.CanConvertTo(context, destinationType); + } + + /// <summary>Converts the given <see cref="IQuantity"/> object to <see cref="string"/>, using the specified context and culture information.</summary> + /// <returns>An <see cref="T:System.Object" /> that represents the converted value.</returns> + /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context. </param> + /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo" />. If null is passed, the current culture is assumed. </param> + /// <param name="value">The <see cref="T:System.Object" /> to convert. </param> + /// <param name="destinationType">The <see cref="T:System.Type" /> to convert the <paramref name="value" /> parameter to. </param> + /// <exception cref="T:System.ArgumentNullException">The <paramref name="destinationType" /> parameter is null. </exception> + /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception> + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) + { + DisplayAsUnitAttribute? displayAsUnit = GetAttribute<DisplayAsUnitAttribute>(context); + + if (value is not IQuantity qvalue || destinationType != typeof(string)) + { + return base.ConvertTo(context, culture, value, destinationType); + } + + if (displayAsUnit == null) + { + return qvalue.ToString(culture); + } + + if (displayAsUnit.UnitType == null) + { + return qvalue.ToString(displayAsUnit.Format, culture); + } + + return qvalue.ToUnit(displayAsUnit.UnitType).ToString(displayAsUnit.Format, culture); + } + } +} diff --git a/UnitsNet.Core/QuantityValue.cs b/UnitsNet.Core/QuantityValue.cs new file mode 100644 index 0000000000..16663d7980 --- /dev/null +++ b/UnitsNet.Core/QuantityValue.cs @@ -0,0 +1,340 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using System.Globalization; +using UnitsNet.InternalHelpers; + +namespace UnitsNet +{ + /// <summary> + /// A type that supports implicit cast from all .NET numeric types, in order to avoid a large number of overloads + /// and binary size for all From(value, unit) factory methods, for each of the 700+ units in the library. + /// <see cref="QuantityValue"/> stores the value internally with the proper type to preserve the range or precision of the original value: + /// <list type="bullet"> + /// <item><description><see cref="double"/> for [byte, short, int, long, float, double]</description></item> + /// <item><description><see cref="decimal"/> for [decimal] to preserve the 128-bit precision</description></item> + /// </list> + /// </summary> + /// <remarks> + /// <para>At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th: + /// From 8 (int, long, double, decimal + each nullable) down to 2 (QuantityValue and QuantityValue?). + /// This also adds more numeric types with no extra overhead, such as float, short and byte.</para> + /// <para>So far, the internal representation can be either <see cref="double"/> or <see cref="decimal"/>, + /// but as this struct is realized as a union struct with overlapping fields, only the amount of memory of the largest data type is used. + /// This allows for adding support for smaller data types without increasing the overall size.</para> + /// </remarks> + [StructLayout(LayoutKind.Explicit)] + [DebuggerDisplay("{GetDebugRepresentation()}")] + public readonly struct QuantityValue : IFormattable, IEquatable<QuantityValue>, IComparable<QuantityValue>, IComparable + { + /// <summary> + /// The value 0 + /// </summary> + public static readonly QuantityValue Zero = new QuantityValue(0, 0); + + /// <summary> + /// Value assigned when implicitly casting from all numeric types except <see cref="decimal" />, since + /// <see cref="double" /> has the greatest range. + /// </summary> + [FieldOffset(8)] // so that it does not interfere with the Type field + private readonly double _doubleValue; + + /// <summary> + /// Value assigned when implicitly casting from <see cref="decimal" /> type, since it has a greater precision than + /// <see cref="double"/> and we want to preserve that when constructing quantities that use <see cref="decimal"/> + /// as their value type. + /// </summary> + [FieldOffset(0)] + // bytes layout: 0-1 unused, 2 exponent, 3 sign (only highest bit), 4-15 number + private readonly decimal _decimalValue; + + /// <summary> + /// Determines the underlying type of this <see cref="QuantityValue"/>. + /// </summary> + [FieldOffset(0)] // using unused byte for storing type + public readonly UnderlyingDataType Type; + + private QuantityValue(double val) : this() + { + _doubleValue = Guard.EnsureValidNumber(val, nameof(val)); + Type = UnderlyingDataType.Double; + } + + private QuantityValue(decimal val) : this() + { + _decimalValue = val; + Type = UnderlyingDataType.Decimal; + } + + private QuantityValue(double value, decimal valueDecimal) : this() + { + if (valueDecimal != 0) + { + _decimalValue = valueDecimal; + Type = UnderlyingDataType.Decimal; + } + else + { + _doubleValue = value; + Type = UnderlyingDataType.Double; + } + } + + /// <summary> + /// Returns true if the underlying value is stored as a decimal + /// </summary> + public bool IsDecimal => Type == UnderlyingDataType.Decimal; + + #region To QuantityValue + + // Prefer double for integer types, since most quantities use that type as of now and + // that avoids unnecessary casts back and forth. + // If we later change to use decimal more, we should revisit this. + /// <summary>Implicit cast from <see cref="byte"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(byte val) => new QuantityValue((double) val); + /// <summary>Implicit cast from <see cref="short"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(short val) => new QuantityValue((double) val); + /// <summary>Implicit cast from <see cref="int"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(int val) => new QuantityValue((double) val); + /// <summary>Implicit cast from <see cref="long"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(long val) => new QuantityValue((double) val); + /// <summary>Implicit cast from <see cref="float"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(float val) => new QuantityValue(val); // double + /// <summary>Implicit cast from <see cref="double"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(double val) => new QuantityValue(val); // double + /// <summary>Implicit cast from <see cref="decimal"/> to <see cref="QuantityValue"/>.</summary> + public static implicit operator QuantityValue(decimal val) => new QuantityValue(val); // decimal + #endregion + + #region To double + + /// <summary>Explicit cast from <see cref="QuantityValue"/> to <see cref="double"/>.</summary> + public static explicit operator double(QuantityValue number) + => number.Type switch + { + UnderlyingDataType.Decimal => (double)number._decimalValue, + UnderlyingDataType.Double => number._doubleValue, + _ => throw new NotImplementedException() + }; + + #endregion + + #region To decimal + + /// <summary>Explicit cast from <see cref="QuantityValue"/> to <see cref="decimal"/>.</summary> + public static explicit operator decimal(QuantityValue number) + => number.Type switch + { + UnderlyingDataType.Decimal => number._decimalValue, + UnderlyingDataType.Double => (decimal)number._doubleValue, + _ => throw new NotImplementedException() + }; + + #endregion + + #region Operators and Comparators + + /// <inheritdoc /> + public override bool Equals(object? other) + { + if (other is QuantityValue qv) + { + return Equals(qv); + } + + return false; + } + + /// <inheritdoc /> + public override int GetHashCode() + { + if (IsDecimal) + { + return _decimalValue.GetHashCode(); + } + else + { + return _doubleValue.GetHashCode(); + } + } + + /// <summary> + /// Performs an equality comparison on two instances of <see cref="QuantityValue"/>. + /// Note that rounding might occur if the two values don't use the same base type. + /// </summary> + /// <param name="other">The value to compare to</param> + /// <returns>True on exact equality, false otherwise</returns> + public bool Equals(QuantityValue other) + { + return CompareTo(other) == 0; + } + + /// <summary>Equality comparator</summary> + public static bool operator ==(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) == 0; + } + + /// <summary>Inequality comparator</summary> + public static bool operator !=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) != 0; + } + + /// <summary> + /// Greater-than operator + /// </summary> + public static bool operator >(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) > 0; + } + + /// <summary> + /// Less-than operator + /// </summary> + public static bool operator <(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) < 0; + } + + /// <summary> + /// Greater-than-or-equal operator + /// </summary> + public static bool operator >=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) >= 0; + } + + /// <summary> + /// Less-than-or-equal operator + /// </summary> + public static bool operator <=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) <= 0; + } + + /// <inheritdoc /> + public int CompareTo(QuantityValue other) + { + if (IsDecimal && other.IsDecimal) + { + return _decimalValue.CompareTo(other._decimalValue); + } + else if (IsDecimal) + { + return _decimalValue.CompareTo((decimal)other._doubleValue); + } + else if (other.IsDecimal) + { + return ((decimal)_doubleValue).CompareTo(other._decimalValue); + } + else + { + return _doubleValue.CompareTo(other._doubleValue); + } + } + + /// <inheritdoc /> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is QuantityValue other)) throw new ArgumentException("Expected type QuantityValue.", nameof(obj)); + + return CompareTo(other); + } + + /// <summary> + /// Returns the negated value of the operand + /// </summary> + /// <param name="v">Value to negate</param> + /// <returns>-v</returns> + public static QuantityValue operator -(QuantityValue v) + { + if (v.IsDecimal) + { + return new QuantityValue(-v._decimalValue); + } + else + { + return new QuantityValue(-v._doubleValue); + } + } + + #endregion + + /// <summary>Returns the string representation of the numeric value.</summary> + public override string ToString() + => Type switch + { + UnderlyingDataType.Decimal => _decimalValue.ToString(CultureInfo.CurrentCulture), + UnderlyingDataType.Double => _doubleValue.ToString(CultureInfo.CurrentCulture), + _ => throw new NotImplementedException() + }; + + private string GetDebugRepresentation() + { + StringBuilder builder = new($"{Type} {ToString()} Hex:"); + + byte[] bytes = BytesUtility.GetBytes(this); + for (int i = bytes.Length - 1; i >= 0; i--) + { + builder.Append($" {bytes[i]:X2}"); + } + + return builder.ToString(); + } + + /// <summary> + /// Returns the string representation of the numeric value, formatted using the given standard numeric format string + /// </summary> + /// <param name="format">A standard numeric format string (must be valid for either double or decimal, depending on the base type)</param> + /// <returns>The string representation</returns> + public string ToString(string format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <summary> + /// Returns the string representation of the numeric value, formatted using the given standard numeric format string + /// </summary> + /// <param name="formatProvider">The culture to use</param> + /// <returns>The string representation</returns> + public string ToString(IFormatProvider formatProvider) + { + return ToString(string.Empty, formatProvider); + } + + /// <summary> + /// Returns the string representation of the underlying value + /// </summary> + /// <param name="format">Standard format specifiers. Because the underlying value can be double or decimal, the meaning can vary</param> + /// <param name="formatProvider">Culture specific settings</param> + /// <returns>A string representation of the number</returns> + public string ToString(string? format, IFormatProvider? formatProvider) + { + if (IsDecimal) + { + return _decimalValue.ToString(format, formatProvider); + } + else + { + return _doubleValue.ToString(format, formatProvider); + } + } + + /// <summary> + /// Describes the underlying type of a <see cref="QuantityValue"/>. + /// </summary> + public enum UnderlyingDataType : byte + { + /// <summary><see cref="Decimal"/> must have the value 0 due to the bit structure of <see cref="decimal"/>.</summary> + Decimal = 0, + /// <inheritdoc cref="double"/> + Double = 1 + } + } +} diff --git a/UnitsNet.Core/UnitConverter.cs b/UnitsNet.Core/UnitConverter.cs new file mode 100644 index 0000000000..c4c7f98ea7 --- /dev/null +++ b/UnitsNet.Core/UnitConverter.cs @@ -0,0 +1,588 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Reflection; +using System.Linq; + +namespace UnitsNet +{ + using ConversionFunctionLookupKey = ValueTuple<Type, Enum, Type, Enum>; + + /// <summary> + /// + /// </summary> + /// <param name="inputValue"></param> + /// <returns></returns> + public delegate IQuantity ConversionFunction(IQuantity inputValue); + + /// <summary> + /// + /// </summary> + /// <typeparam name="TQuantity"></typeparam> + /// <param name="inputValue"></param> + /// <returns></returns> + public delegate TQuantity ConversionFunction<TQuantity>(TQuantity inputValue) + where TQuantity : IQuantity; + + /// <summary> + /// Convert between units of a quantity, such as converting from meters to centimeters of a given length. + /// </summary> + public sealed class UnitConverter + { + /// <summary> + /// The static instance used by Units.NET to convert between units. Modify this to add/remove conversion functions at runtime, such + /// as adding your own third-party units and quantities to convert between. + /// </summary> + public static UnitConverter Default { get; } + + static UnitConverter() + { + Default = new UnitConverter(); + RegisterDefaultConversions(Default); + } + + /// <summary> + /// Creates a new <see cref="UnitConverter"/> instance. + /// </summary> + public UnitConverter() + { + ConversionFunctions = new ConcurrentDictionary<ConversionFunctionLookupKey, ConversionFunction>(); + } + + /// <summary> + /// Creates a new <see cref="UnitConverter"/> instance with the <see cref="ConversionFunction"/> copied from <paramref name="other"/>. + /// </summary> + /// <param name="other">The <see cref="UnitConverter"/> to copy from.</param> + public UnitConverter(UnitConverter other) + { + ConversionFunctions = new ConcurrentDictionary<ConversionFunctionLookupKey, ConversionFunction>(other.ConversionFunctions); + } + + private ConcurrentDictionary<ConversionFunctionLookupKey, ConversionFunction> ConversionFunctions + { + get; + } + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + public static void RegisterDefaultConversions(UnitConverter unitConverter) + { + if (unitConverter is null) + throw new ArgumentNullException(nameof(unitConverter)); + + foreach (var quantity in Quantity.QuantityTypes) + { + // TODO Cache reflection. + var registerMethod = quantity.GetMethod("RegisterDefaultConversions", BindingFlags.NonPublic | BindingFlags.Static); + registerMethod?.Invoke(null, new object[]{unitConverter}); + } + } + + /// <summary> + /// Sets the conversion function from two units of the same quantity type. + /// </summary> + /// <typeparam name="TQuantity">The type of quantity, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + public void SetConversionFunction<TQuantity>(Enum from, Enum to, ConversionFunction<TQuantity> conversionFunction) + where TQuantity : IQuantity + { + var quantityType = typeof(TQuantity); + var conversionLookup = new ConversionFunctionLookupKey(quantityType, from, quantityType, to); + SetConversionFunction(conversionLookup, conversionFunction); + } + + /// <summary> + /// Sets the conversion function from two units of different quantity types. + /// </summary> + /// <typeparam name="TQuantityFrom">From quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <typeparam name="TQuantityTo">To quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + public void SetConversionFunction<TQuantityFrom, TQuantityTo>(Enum from, Enum to, ConversionFunction conversionFunction) + where TQuantityFrom : IQuantity + where TQuantityTo : IQuantity + { + SetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to, conversionFunction); + } + + /// <summary> + /// Sets the conversion function from two units of different quantity types. + /// </summary> + /// <param name="fromType">From quantity type, must implement <see cref="IQuantity"/>.</param> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="toType">To quantity type, must implement <see cref="IQuantity"/>.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to, ConversionFunction conversionFunction) + { + var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); + SetConversionFunction(conversionLookup, conversionFunction); + } + + /// <summary> + /// Sets the conversion function for a particular conversion function lookup. + /// </summary> + /// <param name="lookupKey">The lookup key.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + internal void SetConversionFunction(ConversionFunctionLookupKey lookupKey, ConversionFunction conversionFunction) + { + ConversionFunctions[lookupKey] = conversionFunction; + } + + /// <summary> + /// Sets the conversion function for a particular conversion function lookup. + /// </summary> + /// <typeparam name="TQuantity">The quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="conversionLookup">The quantity conversion function lookup key.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + internal void SetConversionFunction<TQuantity>(ConversionFunctionLookupKey conversionLookup, ConversionFunction<TQuantity> conversionFunction) + where TQuantity : IQuantity + { + IQuantity TypelessConversionFunction(IQuantity quantity) => conversionFunction((TQuantity) quantity); + + ConversionFunctions[conversionLookup] = TypelessConversionFunction; + } + + /// <summary> + /// Gets the conversion function from two units of the same quantity type. + /// </summary> + /// <typeparam name="TQuantity">The quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <returns></returns> + public ConversionFunction GetConversionFunction<TQuantity>(Enum from, Enum to) where TQuantity : IQuantity + { + return GetConversionFunction(typeof(TQuantity), from, typeof(TQuantity), to); + } + + /// <summary> + /// Gets the conversion function from two units of different quantity types. + /// </summary> + /// <typeparam name="TQuantityFrom">From quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <typeparam name="TQuantityTo">To quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <returns></returns> + public ConversionFunction GetConversionFunction<TQuantityFrom, TQuantityTo>(Enum from, Enum to) + where TQuantityFrom : IQuantity + where TQuantityTo : IQuantity + { + return GetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to); + } + + /// <summary> + /// Gets the conversion function from two units of different quantity types. + /// </summary> + /// <param name="fromType">From quantity type, must implement <see cref="IQuantity"/>.</param> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="toType">To quantity type, must implement <see cref="IQuantity"/>.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + public ConversionFunction GetConversionFunction(Type fromType, Enum from, Type toType, Enum to) + { + var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); + return GetConversionFunction(conversionLookup); + } + + /// <summary> + /// Gets the conversion function by its lookup key. + /// </summary> + /// <param name="lookupKey"></param> + internal ConversionFunction GetConversionFunction(ConversionFunctionLookupKey lookupKey) + { + IQuantity EchoFunction(IQuantity fromQuantity) => fromQuantity; + + // If from/to units and to quantity types are equal, then return a function that echoes the input quantity + // in order to not have to map conversion functions to "self". + if (lookupKey.Item1 == lookupKey.Item3 && Equals(lookupKey.Item2, lookupKey.Item4)) + return EchoFunction; + + return ConversionFunctions[lookupKey]; + } + + /// <summary> + /// Gets the conversion function for two units of the same quantity type. + /// </summary> + /// <typeparam name="TQuantity">The quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + /// <returns>true if set; otherwise, false.</returns> + public bool TryGetConversionFunction<TQuantity>(Enum from, Enum to, [NotNullWhen(true)] out ConversionFunction? conversionFunction) where TQuantity : IQuantity + { + return TryGetConversionFunction(typeof(TQuantity), from, typeof(TQuantity), to, out conversionFunction); + } + + /// <summary> + /// Gets the conversion function for two units of different quantity types. + /// </summary> + /// <typeparam name="TQuantityFrom">From quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <typeparam name="TQuantityTo">To quantity type, must implement <see cref="IQuantity"/>.</typeparam> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + /// <returns>true if set; otherwise, false.</returns> + public bool TryGetConversionFunction<TQuantityFrom, TQuantityTo>(Enum from, Enum to, [NotNullWhen(true)] out ConversionFunction? conversionFunction) + where TQuantityFrom : IQuantity + where TQuantityTo : IQuantity + { + return TryGetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to, out conversionFunction); + } + + /// <summary> + /// Try to get the conversion function for two units of the same quantity type. + /// </summary> + /// <param name="fromType">From quantity type, must implement <see cref="IQuantity"/>.</param> + /// <param name="from">From unit enum value, such as <see cref="LengthUnit.Kilometer" />.</param> + /// <param name="toType">To quantity type, must implement <see cref="IQuantity"/>.</param> + /// <param name="to">To unit enum value, such as <see cref="LengthUnit.Centimeter"/>.</param> + /// <param name="conversionFunction">The quantity conversion function.</param> + /// <returns>true if set; otherwise, false.</returns> + public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum to, [NotNullWhen(true)] out ConversionFunction? conversionFunction) + { + var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); + return TryGetConversionFunction(conversionLookup, out conversionFunction); + } + + /// <summary> + /// + /// </summary> + /// <param name="lookupKey"></param> + /// <param name="conversionFunction"></param> + /// <returns>true if set; otherwise, false.</returns> + public bool TryGetConversionFunction(ConversionFunctionLookupKey lookupKey, [NotNullWhen(true)] out ConversionFunction? conversionFunction) + { + return ConversionFunctions.TryGetValue(lookupKey, out conversionFunction); + } + + /// <summary> + /// Convert between any two quantity units given a numeric value and two unit enum values. + /// </summary> + /// <param name="fromValue">Numeric value.</param> + /// <param name="fromUnitValue">From unit enum value.</param> + /// <param name="toUnitValue">To unit enum value, must be compatible with <paramref name="fromUnitValue" />.</param> + /// <returns>The converted value in the new unit representation.</returns> + public static double Convert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue) + { + return Quantity + .From(fromValue, fromUnitValue) + .As(toUnitValue); + } + + /// <summary> + /// Try to convert between any two quantity units given a numeric value and two unit enum values. + /// </summary> + /// <param name="fromValue">Numeric value.</param> + /// <param name="fromUnitValue">From unit enum value.</param> + /// <param name="toUnitValue">To unit enum value, must be compatible with <paramref name="fromUnitValue" />.</param> + /// <param name="convertedValue">The converted value, if successful. Otherwise default.</param> + /// <returns>True if successful.</returns> + public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue, out double convertedValue) + { + convertedValue = 0; + if (!Quantity.TryFrom(fromValue, fromUnitValue, out IQuantity? fromQuantity)) + return false; + + try + { + // We're not going to implement TryAs() in all quantities, so let's just try-catch here + convertedValue = fromQuantity.As(toUnitValue); + return true; + } + catch + { + return false; + } + } + + /// <summary> + /// Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// </summary> + /// <param name="fromValue"> + /// Input value, which together with <paramref name="fromUnit" /> represents the quantity to + /// convert from. + /// </param> + /// <param name="quantityName"> + /// The name of the quantity, such as "Length" or "Mass". See <see cref="Quantity.Infos" /> for all + /// types generated by UnitsNet and use <see cref="UnitInfo.Name"/>. + /// </param> + /// <param name="fromUnit"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="toUnit"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <example>double centimeters = ConvertByName(5, "Length", "Meter", "Centimeter"); // 500</example> + /// <returns>Output value as the result of converting to <paramref name="toUnit" />.</returns> + /// <exception cref="UnitNotFoundException">No units match the abbreviation.</exception> + /// <exception cref="AmbiguousUnitParseException">More than one unit matches the abbreviation.</exception> + public static double ConvertByName(QuantityValue fromValue, string quantityName, string fromUnit, string toUnit) + { + if (!TryGetUnitType(quantityName, out Type? unitType)) + throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); + + if (!TryParseUnit(unitType!, fromUnit, out Enum? fromUnitValue)) // ex: LengthUnit.Meter + { + var e = new UnitNotFoundException($"Unit not found [{fromUnit}]."); + e.Data["unitName"] = fromUnit; + throw e; + } + + if (!TryParseUnit(unitType!, toUnit, out Enum? toUnitValue)) // ex: LengthUnit.Centimeter + { + var e = new UnitNotFoundException($"Unit not found [{toUnit}]."); + e.Data["unitName"] = toUnit; + throw e; + } + + return Convert(fromValue, fromUnitValue!, toUnitValue!); + } + + /// <summary> + /// Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// </summary> + /// <param name="inputValue"> + /// Input value, which together with <paramref name="fromUnit" /> represents the quantity to + /// convert from. + /// </param> + /// <param name="quantityName"> + /// The name of the quantity, such as "Length" or "Mass". See <see cref="Quantity.Infos" /> for all + /// types generated by UnitsNet and use <see cref="UnitInfo.Name"/>. + /// </param> + /// <param name="fromUnit"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="toUnit"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="result">Result if conversion was successful, 0 if not.</param> + /// <example>bool ok = TryConvertByName(5, "Length", "Meter", "Centimeter", out double centimeters); // 500</example> + /// <returns>True if conversion was successful.</returns> + public static bool TryConvertByName(QuantityValue inputValue, string quantityName, string fromUnit, string toUnit, out double result) + { + result = 0d; + + if (!TryGetUnitType(quantityName, out Type? unitType)) + return false; + + if (!TryParseUnit(unitType!, fromUnit, out Enum? fromUnitValue)) // ex: LengthUnit.Meter + return false; + + if (!TryParseUnit(unitType!, toUnit, out Enum? toUnitValue)) // ex: LengthUnit.Centimeter + return false; + + result = Convert(inputValue, fromUnitValue!, toUnitValue!); + return true; + } + + /// <summary> + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// </summary> + /// <param name="fromValue"> + /// Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to + /// convert from. + /// </param> + /// <param name="quantityName"> + /// Name of quantity, such as "Length" and "Mass". <see cref="QuantityInfo" /> for all + /// values. + /// </param> + /// <param name="fromUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="toUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example> + /// <returns>Output value as the result of converting to <paramref name="toUnitAbbrev" />.</returns> + public static double ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) + { + return ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, null); + } + + /// <summary> + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// </summary> + /// <param name="fromValue"> + /// Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to + /// convert from. + /// </param> + /// <param name="quantityName"> + /// The name of the quantity, such as "Length" or "Mass". See <see cref="Quantity.Infos" /> for all + /// types generated by UnitsNet and use <see cref="UnitInfo.Name"/>. + /// </param> + /// <param name="fromUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="toUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="culture">Culture to parse abbreviations with.</param> + /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example> + /// <returns>Output value as the result of converting to <paramref name="toUnitAbbrev" />.</returns> + /// <exception cref="UnitNotFoundException"> + /// No unit types match the prefix of <paramref name="quantityName" /> or no units + /// are mapped to the abbreviation. + /// </exception> + /// <exception cref="AmbiguousUnitParseException">More than one unit matches the abbreviation.</exception> + public static double ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string? culture) + { + if (!TryGetUnitType(quantityName, out Type? unitType)) + throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); + + var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentCulture : new CultureInfo(culture); + + var fromUnit = UnitParser.Default.Parse(fromUnitAbbrev, unitType!, cultureInfo); // ex: ("m", LengthUnit) => LengthUnit.Meter + var fromQuantity = Quantity.From(fromValue, fromUnit); + + var toUnit = UnitParser.Default.Parse(toUnitAbbrev, unitType!, cultureInfo); // ex:("cm", LengthUnit) => LengthUnit.Centimeter + return fromQuantity.As(toUnit); + } + + /// <summary> + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// </summary> + /// <param name="fromValue"> + /// Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to + /// convert from. + /// </param> + /// <param name="quantityName"> + /// The name of the quantity, such as "Length" or "Mass". See <see cref="Quantity.Infos" /> for all + /// types generated by UnitsNet and use <see cref="UnitInfo.Name"/>. + /// </param> + /// <param name="fromUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="toUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="result">Result if conversion was successful, 0 if not.</param> + /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example> + /// <returns>True if conversion was successful.</returns> + public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result) + { + return TryConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result, null); + } + + /// <summary> + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// </summary> + /// <param name="fromValue"> + /// Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to + /// convert from. + /// </param> + /// <param name="quantityName"> + /// The name of the quantity, such as "Length" or "Mass". See <see cref="Quantity.Infos" /> for all + /// types generated by UnitsNet and use <see cref="UnitInfo.Name"/>. + /// </param> + /// <param name="fromUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="toUnitAbbrev"> + /// Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as + /// <paramref name="quantityName" />. + /// </param> + /// <param name="culture">Culture to parse abbreviations with.</param> + /// <param name="result">Result if conversion was successful, 0 if not.</param> + /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example> + /// <returns>True if conversion was successful.</returns> + public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result, + string? culture) + { + result = 0d; + + if (!TryGetUnitType(quantityName, out Type? unitType)) + return false; + + var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentCulture : new CultureInfo(culture); + + if (!UnitParser.Default.TryParse(fromUnitAbbrev, unitType!, cultureInfo, out Enum? fromUnit)) // ex: ("m", LengthUnit) => LengthUnit.Meter + return false; + + if (!UnitParser.Default.TryParse(toUnitAbbrev, unitType!, cultureInfo, out Enum? toUnit)) // ex:("cm", LengthUnit) => LengthUnit.Centimeter + return false; + + var fromQuantity = Quantity.From(fromValue, fromUnit); + result = fromQuantity.As(toUnit); + + return true; + } + + /// <summary> + /// Parse a unit by the unit enum type <paramref name="unitType" /> and a unit enum value <paramref name="unitName" />> + /// </summary> + /// <param name="unitType">Unit type, such as <see cref="LengthUnit" />.</param> + /// <param name="unitName">Unit name, such as "Meter" corresponding to <see cref="LengthUnit.Meter" />.</param> + /// <param name="unitValue">The return enum value, such as <see cref="LengthUnit.Meter" /> boxed as an object.</param> + /// <returns>True if succeeded, otherwise false.</returns> + /// <exception cref="UnitNotFoundException">No unit values match the <paramref name="unitName" />.</exception> + private static bool TryParseUnit(Type unitType, string unitName, out Enum? unitValue) + { + unitValue = null; + var eNames = Enum.GetNames(unitType); + var matchedUnitName = eNames.FirstOrDefault(x => x.Equals(unitName, StringComparison.OrdinalIgnoreCase)); + if (matchedUnitName == null) + return false; + + unitValue = (Enum) Enum.Parse(unitType, matchedUnitName); + return true; + } + + private static bool TryGetUnitType(string quantityName, out Type? unitType) + { + var quantityInfo = Quantity.Infos.FirstOrDefault(info => info.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); + + unitType = quantityInfo?.UnitType; + return quantityInfo != null; + } + } +} + diff --git a/UnitsNet.Core/UnitFormatter.cs b/UnitsNet.Core/UnitFormatter.cs new file mode 100644 index 0000000000..06ecbbf700 --- /dev/null +++ b/UnitsNet.Core/UnitFormatter.cs @@ -0,0 +1,80 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UnitsNet +{ + /// <summary> + /// Utility class for formatting units and values. + /// </summary> + internal static class UnitFormatter + { + /// <summary> + /// Gets the default ToString format for the specified value. + /// </summary> + /// <param name="value">The value to format.</param> + /// <param name="significantDigitsAfterRadix"> + /// The number of digits after the radix point to display in the formatted + /// string. + /// </param> + /// <returns>A ToString format for the specified value.</returns> + public static string GetFormat(double value, int significantDigitsAfterRadix) + { + double v = Math.Abs(value); + var sigDigitsAfterRadixStr = new string('#', significantDigitsAfterRadix); + string format; + + if (NearlyEqual(v, 0)) + { + format = "{0} {1}"; + } + // Values below 1e-3 are displayed in scientific notation. + else if (v < 1e-3) + { + format = "{0:0." + sigDigitsAfterRadixStr + "e-00} {1}"; + } + // Values from 1e-3 to 1 use fixed point notation. + else if ((v > 1e-4) && (v < 1)) + { + format = "{0:g" + significantDigitsAfterRadix + "} {1}"; + } + // Values between 1 and 1e5 use fixed point notation with digit grouping. + else if ((v >= 1) && (v < 1e6)) + { + // The comma will be automatically replaced with the correct digit separator if a different culture is used. + format = "{0:#,0." + sigDigitsAfterRadixStr + "} {1}"; + } + // Values above 1e5 use scientific notation. + else + { + format = "{0:0." + sigDigitsAfterRadixStr + "e+00} {1}"; + } + + return format; + } + + private static bool NearlyEqual(double a, double b) + { + return Math.Abs(a - b) < 1e-150; + } + + /// <summary> + /// Gets ToString format arguments. + /// </summary> + /// <typeparam name="TUnitType">The type of units to format.</typeparam> + /// <param name="unit">The units</param> + /// <param name="value">The unit value to format.</param> + /// <param name="culture">The current culture.</param> + /// <param name="args">The list of format arguments.</param> + /// <returns>An array of ToString format arguments.</returns> + public static object[] GetFormatArgs<TUnitType>(TUnitType unit, double value, IFormatProvider? culture, IEnumerable<object> args) + where TUnitType : Enum + { + string abbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), culture); + return new object[] {value, abbreviation}.Concat(args).ToArray(); + } + } +} diff --git a/UnitsNet.Core/UnitInfo.cs b/UnitsNet.Core/UnitInfo.cs new file mode 100644 index 0000000000..dd3f6e6cd8 --- /dev/null +++ b/UnitsNet.Core/UnitInfo.cs @@ -0,0 +1,81 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; + +namespace UnitsNet +{ + /// <summary> + /// Information about the unit, such as its name and value. + /// This is useful to enumerate units and present names with quantities and units + /// chosen dynamically at runtime, such as unit conversion apps or allowing the user to change the + /// unit representation. + /// </summary> + /// <remarks> + /// Typically you obtain this by looking it up via <see cref="QuantityInfo.UnitInfos" />. + /// </remarks> + public class UnitInfo + { + /// <summary> + /// Creates an instance of the UnitInfo class. + /// </summary> + /// <param name="value">The enum value for this class, for example <see cref="LengthUnit.Meter"/>.</param> + /// <param name="pluralName">The plural name of the unit, such as "Centimeters".</param> + /// <param name="abbreviations">One or more abbreviations for this unit, with the first one being the default abbreviation.</param> + /// <param name="baseUnits">The <see cref="BaseUnits"/> for this unit.</param> + public UnitInfo(Enum value, string pluralName, IReadOnlyList<string> abbreviations, BaseUnits baseUnits) + { + Value = value ?? throw new ArgumentNullException(nameof(value)); + Name = value.ToString(); + PluralName = pluralName ?? throw new ArgumentNullException(nameof(pluralName)); + Abbreviations = abbreviations ?? throw new ArgumentNullException(nameof(abbreviations)); + BaseUnits = baseUnits ?? throw new ArgumentNullException(nameof(baseUnits)); + } + + /// <summary> + /// One or more abbreviations for this unit, with the first one being the default abbreviation. + /// </summary> + public IReadOnlyList<string> Abbreviations { get; } + + /// <summary> + /// The enum value of the unit, such as <see cref="LengthUnit.Centimeter" />. + /// </summary> + public Enum Value { get; } + + /// <summary> + /// The singular name of the unit, such as "Centimeter". + /// </summary> + public string Name { get; } + + /// <summary> + /// The plural name of the unit, such as "Centimeters". + /// </summary> + public string PluralName { get; } + + /// <summary> + /// Gets the <see cref="BaseUnits"/> for this unit. + /// </summary> + public BaseUnits BaseUnits { get; } + } + + /// <inheritdoc cref="UnitInfo" /> + /// <remarks> + /// This is a specialization of <see cref="UnitInfo" />, for when the unit type is known. + /// Typically you obtain this by looking it up statically from <see cref="QuantityInfo{LengthUnit}.UnitInfos" /> or + /// or dynamically via <see cref="IQuantity{TUnitType}.QuantityInfo" />. + /// </remarks> + /// <typeparam name="TUnit">The unit enum type, such as <see cref="LengthUnit" />. </typeparam> + public class UnitInfo<TUnit> : UnitInfo + where TUnit : Enum + { + /// <inheritdoc /> + public UnitInfo(TUnit value, string pluralName, IReadOnlyList<string> abbreviations, BaseUnits baseUnits) : base(value, pluralName, abbreviations, baseUnits) + { + Value = value; + } + + /// <inheritdoc cref="UnitInfo.Value"/> + public new TUnit Value { get; } + } +} diff --git a/UnitsNet.Core/UnitMath.cs b/UnitsNet.Core/UnitMath.cs new file mode 100644 index 0000000000..f9ab87d1c8 --- /dev/null +++ b/UnitsNet.Core/UnitMath.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UnitsNet +{ + /// <summary> + /// A set of extension methods for some of the most common Math operations, such as Min, Max, Sum and Average + /// </summary> + public static class UnitMath + { + /// <summary>Returns the absolute value of a <typeparamref name="TQuantity" />.</summary> + /// <param name="value"> + /// A quantity with a value that is greater than or equal to <see cref="F:System.Double.MinValue" />, + /// but less than or equal to <see cref="F:System.Double.MaxValue" />. + /// </param> + /// <returns>A quantity with a value, such that 0 ≤ value ≤ <see cref="F:System.Double.MaxValue" />.</returns> + public static TQuantity Abs<TQuantity>(this TQuantity value) where TQuantity : IQuantity + { + return value.Value >= QuantityValue.Zero ? value : (TQuantity) Quantity.From(-value.Value, value.Unit); + } + + /// <summary>Computes the sum of a sequence of <typeparamref name="TQuantity" /> values.</summary> + /// <param name="source">A sequence of <typeparamref name="TQuantity" /> values to calculate the sum of.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <returns>The sum of the values in the sequence, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> is null. + /// </exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Sum<TQuantity>(this IEnumerable<TQuantity> source, Enum unitType) + where TQuantity : IQuantity + { + return (TQuantity) Quantity.From(source.Sum(x => x.As(unitType)), unitType); + } + + /// <summary> + /// Computes the sum of the sequence of <typeparamref name="TQuantity" /> values that are obtained by invoking a + /// transform function on each element of the input sequence. + /// </summary> + /// <param name="source">A sequence of values that are used to calculate a sum.</param> + /// <param name="selector">A transform function to apply to each element.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <typeparam name="TSource">The type of the elements of source.</typeparam> + /// <typeparam name="TQuantity">The type of quantity that is produced by this operation</typeparam> + /// <returns>The sum of the projected values, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> or <paramref name="selector">selector</paramref> is null. + /// </exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Sum<TSource, TQuantity>(this IEnumerable<TSource> source, Func<TSource, TQuantity> selector, Enum unitType) + where TQuantity : IQuantity + { + return source.Select(selector).Sum(unitType); + } + + /// <summary>Returns the smaller of two <typeparamref name="TQuantity" /> values.</summary> + /// <typeparam name="TQuantity">The type of quantities to compare.</typeparam> + /// <param name="val1">The first of two <typeparamref name="TQuantity" /> values to compare.</param> + /// <param name="val2">The second of two <typeparamref name="TQuantity" /> values to compare.</param> + /// <returns>Parameter <paramref name="val1" /> or <paramref name="val2" />, whichever is smaller.</returns> + public static TQuantity Min<TQuantity>(TQuantity val1, TQuantity val2) where TQuantity : IComparable, IQuantity + { + return val1.CompareTo(val2) == 1 ? val2 : val1; + } + + /// <summary>Computes the min of a sequence of <typeparamref name="TQuantity" /> values.</summary> + /// <param name="source">A sequence of <typeparamref name="TQuantity" /> values to calculate the min of.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <returns>The min of the values in the sequence, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> is null. + /// </exception> + /// <exception cref="T:System.InvalidOperationException"><paramref name="source">source</paramref> contains no elements.</exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Min<TQuantity>(this IEnumerable<TQuantity> source, Enum unitType) + where TQuantity : IQuantity + { + return (TQuantity) Quantity.From(source.Min(x => x.As(unitType)), unitType); + } + + /// <summary> + /// Computes the min of the sequence of <typeparamref name="TQuantity" /> values that are obtained by invoking a + /// transform function on each element of the input sequence. + /// </summary> + /// <param name="source">A sequence of values that are used to calculate a min.</param> + /// <param name="selector">A transform function to apply to each element.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <typeparam name="TSource">The type of the elements of source.</typeparam> + /// <typeparam name="TQuantity">The type of quantity that is produced by this operation</typeparam> + /// <returns>The min of the projected values, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> or <paramref name="selector">selector</paramref> is null. + /// </exception> + /// <exception cref="T:System.InvalidOperationException"><paramref name="source">source</paramref> contains no elements.</exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Min<TSource, TQuantity>(this IEnumerable<TSource> source, Func<TSource, TQuantity> selector, Enum unitType) + where TQuantity : IQuantity + { + return source.Select(selector).Min(unitType); + } + + /// <summary>Returns the larger of two <typeparamref name="TQuantity" /> values.</summary> + /// <typeparam name="TQuantity">The type of quantities to compare.</typeparam> + /// <param name="val1">The first of two <typeparamref name="TQuantity" /> values to compare.</param> + /// <param name="val2">The second of two <typeparamref name="TQuantity" /> values to compare.</param> + /// <returns>Parameter <paramref name="val1" /> or <paramref name="val2" />, whichever is larger.</returns> + public static TQuantity Max<TQuantity>(TQuantity val1, TQuantity val2) where TQuantity : IComparable, IQuantity + { + return val1.CompareTo(val2) == -1 ? val2 : val1; + } + + /// <summary>Computes the max of a sequence of <typeparamref name="TQuantity" /> values.</summary> + /// <param name="source">A sequence of <typeparamref name="TQuantity" /> values to calculate the max of.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <returns>The max of the values in the sequence, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> is null. + /// </exception> + /// <exception cref="T:System.InvalidOperationException"><paramref name="source">source</paramref> contains no elements.</exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Max<TQuantity>(this IEnumerable<TQuantity> source, Enum unitType) + where TQuantity : IQuantity + { + return (TQuantity) Quantity.From(source.Max(x => x.As(unitType)), unitType); + } + + /// <summary> + /// Computes the max of the sequence of <typeparamref name="TQuantity" /> values that are obtained by invoking a + /// transform function on each element of the input sequence. + /// </summary> + /// <param name="source">A sequence of values that are used to calculate a max.</param> + /// <param name="selector">A transform function to apply to each element.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <typeparam name="TSource">The type of the elements of source.</typeparam> + /// <typeparam name="TQuantity">The type of quantity that is produced by this operation</typeparam> + /// <returns>The max of the projected values, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> or <paramref name="selector">selector</paramref> is null. + /// </exception> + /// <exception cref="T:System.InvalidOperationException"><paramref name="source">source</paramref> contains no elements.</exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Max<TSource, TQuantity>(this IEnumerable<TSource> source, Func<TSource, TQuantity> selector, Enum unitType) + where TQuantity : IQuantity + { + return source.Select(selector).Max(unitType); + } + + /// <summary>Computes the average of a sequence of <typeparamref name="TQuantity" /> values.</summary> + /// <param name="source">A sequence of <typeparamref name="TQuantity" /> values to calculate the average of.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <returns>The average of the values in the sequence, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> is null. + /// </exception> + /// <exception cref="T:System.InvalidOperationException"><paramref name="source">source</paramref> contains no elements.</exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Average<TQuantity>(this IEnumerable<TQuantity> source, Enum unitType) + where TQuantity : IQuantity + { + return (TQuantity) Quantity.From(source.Average(x => x.As(unitType)), unitType); + } + + /// <summary> + /// Computes the average of the sequence of <typeparamref name="TQuantity" /> values that are obtained by invoking + /// a transform function on each element of the input sequence. + /// </summary> + /// <param name="source">A sequence of values that are used to calculate an average.</param> + /// <param name="selector">A transform function to apply to each element.</param> + /// <param name="unitType">The desired unit type for the resulting quantity</param> + /// <typeparam name="TSource">The type of the elements of source.</typeparam> + /// <typeparam name="TQuantity">The type of quantity that is produced by this operation</typeparam> + /// <returns>The average of the projected values, represented in the specified unit type.</returns> + /// <exception cref="T:System.ArgumentNullException"> + /// <paramref name="source">source</paramref> or <paramref name="selector">selector</paramref> is null. + /// </exception> + /// <exception cref="T:System.InvalidOperationException"><paramref name="source">source</paramref> contains no elements.</exception> + /// <exception cref="ArgumentException"> + /// <paramref name="source">source</paramref> contains quantity types different from <paramref name="unitType" />. + /// </exception> + public static TQuantity Average<TSource, TQuantity>(this IEnumerable<TSource> source, Func<TSource, TQuantity> selector, Enum unitType) + where TQuantity : IQuantity + { + return source.Select(selector).Average(unitType); + } + + /// <summary>Returns <paramref name="value" /> clamped to the inclusive range of <paramref name="min" /> and <paramref name="max" />.</summary> + /// <param name="value">The value to be clamped.</param> + /// <param name="min">The lower bound of the result.</param> + /// <param name="max">The upper bound of the result.</param> + /// <returns> + /// <paramref name="value" /> if <paramref name="min" /> ≤ <paramref name="value" /> ≤ <paramref name="max" />. + /// + /// -or- + /// + /// <paramref name="min" /> (converted to value.Unit) if <paramref name="value" /> < <paramref name="min" />. + /// + /// -or- + /// + /// <paramref name="max" /> (converted to value.Unit) if <paramref name="max" /> < <paramref name="value" />. + /// </returns> + /// <exception cref="ArgumentException"> + /// <paramref name="min" /> cannot be greater than <paramref name="max" />. + /// </exception> + public static TQuantity Clamp<TQuantity>(TQuantity value, TQuantity min, TQuantity max) where TQuantity : IComparable, IQuantity + { + var minValue = (TQuantity)min.ToUnit(value.Unit); + var maxValue = (TQuantity)max.ToUnit(value.Unit); + + if (minValue.CompareTo(maxValue) > 0) + { + throw new ArgumentException($"min ({min}) cannot be greater than max ({max})", nameof(min)); + } + + if (value.CompareTo(minValue) < 0) + { + return minValue; + } + + if (value.CompareTo(maxValue) > 0) + { + return maxValue; + } + + return value; + } + + /// <summary> + /// Explicitly create a <see cref="QuantityValue"/> instance from a double + /// </summary> + /// <param name="value">The input value</param> + /// <returns>An instance of <see cref="QuantityValue"/></returns> + public static QuantityValue ToQuantityValue(this double value) + { + return value; // Implicit cast + } + + /// <summary> + /// Explicitly create a <see cref="QuantityValue"/> instance from a decimal + /// </summary> + /// <param name="value">The input value</param> + /// <returns>An instance of <see cref="QuantityValue"/></returns> + public static QuantityValue ToQuantityValue(this decimal value) + { + return value; // Implicit cast + } + } +} diff --git a/UnitsNet.Core/UnitNotFoundException.cs b/UnitsNet.Core/UnitNotFoundException.cs new file mode 100644 index 0000000000..0a1001e273 --- /dev/null +++ b/UnitsNet.Core/UnitNotFoundException.cs @@ -0,0 +1,29 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +namespace UnitsNet +{ + /// <summary> + /// Unit was not found. This is typically thrown for dynamic conversions, + /// such as <see cref="UnitConverter.ConvertByName" />. + /// </summary> + public class UnitNotFoundException : UnitsNetException + { + /// <inheritdoc /> + public UnitNotFoundException() + { + } + + /// <inheritdoc /> + public UnitNotFoundException(string message) : base(message) + { + } + + /// <inheritdoc /> + public UnitNotFoundException(string message, Exception innerException) : base(message, innerException) + { + } + } +} diff --git a/UnitsNet.Core/UnitsNet.Core.csproj b/UnitsNet.Core/UnitsNet.Core.csproj new file mode 100644 index 0000000000..dd863fd245 --- /dev/null +++ b/UnitsNet.Core/UnitsNet.Core.csproj @@ -0,0 +1,74 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Core</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Description>Common types and abstractions that are required for the UnitsNet packages that adds quantities and units.</Description> + <Title>Units.NET Core</Title> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFrameworks>netstandard2.0;net7.0</TargetFrameworks> + </PropertyGroup> + + <!-- SourceLink: https://github.com/dotnet/sourcelink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + + <!-- Optional: Embed source files that are not tracked by the source control manager in the PDB --> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + + <!-- Optional: Build symbol package (.snupkg) to distribute the PDB containing Source Link --> + <IncludeSymbols>true</IncludeSymbols> + <SymbolPackageFormat>snupkg</SymbolPackageFormat> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet</AssemblyName> + </PropertyGroup> + + <!-- TEMP: Ignore warnings about xmldoc referencing non-existing types, such as Length not being accessible from UnitsNet.Core. + Will fix the xmldoc to not have strong type references. --> + <PropertyGroup> + <NoWarn>$(NoWarn);CS1574;CS1584;CS1581;CS1580</NoWarn> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> + </ItemGroup> + + <!-- Link in common unit definition .json files --> + <ItemGroup> + <None Include="..\Common\**\*"> + <Link>Common\%(RecursiveDir)%(Filename)%(Extension)</Link> + </None> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Core/UnitsNetException.cs b/UnitsNet.Core/UnitsNetException.cs new file mode 100644 index 0000000000..a517b700c2 --- /dev/null +++ b/UnitsNet.Core/UnitsNetException.cs @@ -0,0 +1,31 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; + +namespace UnitsNet +{ + /// <summary> + /// The base type for UnitsNet exceptions. + /// </summary> + public class UnitsNetException : Exception + { + /// <inheritdoc /> + public UnitsNetException() + { + HResult = 1; + } + + /// <inheritdoc /> + public UnitsNetException(string message) : base(message) + { + HResult = 1; + } + + /// <inheritdoc /> + public UnitsNetException(string message, Exception innerException) : base(message, innerException) + { + HResult = 1; + } + } +} diff --git a/UnitsNet.Modular.sln b/UnitsNet.Modular.sln new file mode 100644 index 0000000000..65480b45a2 --- /dev/null +++ b/UnitsNet.Modular.sln @@ -0,0 +1,951 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29609.76 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Acceleration", "UnitsNet.Modular\GeneratedCode\Acceleration\Acceleration.csproj", "{8E3A6691-A05F-D71C-F12A-F537C0807F85}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "AmountOfSubstance", "UnitsNet.Modular\GeneratedCode\AmountOfSubstance\AmountOfSubstance.csproj", "{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "AmplitudeRatio", "UnitsNet.Modular\GeneratedCode\AmplitudeRatio\AmplitudeRatio.csproj", "{59C09A1B-EFF0-E367-6372-D16C4C984916}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Angle", "UnitsNet.Modular\GeneratedCode\Angle\Angle.csproj", "{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ApparentEnergy", "UnitsNet.Modular\GeneratedCode\ApparentEnergy\ApparentEnergy.csproj", "{6F80E841-E953-BC39-6670-8711F2AD9D18}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ApparentPower", "UnitsNet.Modular\GeneratedCode\ApparentPower\ApparentPower.csproj", "{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Area", "UnitsNet.Modular\GeneratedCode\Area\Area.csproj", "{04C24D02-BAD7-A877-FF9B-A36A886C9633}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "AreaDensity", "UnitsNet.Modular\GeneratedCode\AreaDensity\AreaDensity.csproj", "{92FF1332-BF34-943E-A58D-8A76746D879E}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "AreaMomentOfInertia", "UnitsNet.Modular\GeneratedCode\AreaMomentOfInertia\AreaMomentOfInertia.csproj", "{566EF13C-0D17-E465-D35F-1BD9C65559BF}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "BitRate", "UnitsNet.Modular\GeneratedCode\BitRate\BitRate.csproj", "{B5FDF997-829F-5281-E624-EE4EEE5AA26C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "BrakeSpecificFuelConsumption", "UnitsNet.Modular\GeneratedCode\BrakeSpecificFuelConsumption\BrakeSpecificFuelConsumption.csproj", "{085145F2-2B8F-4D09-5290-C14CDCD452BF}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Capacitance", "UnitsNet.Modular\GeneratedCode\Capacitance\Capacitance.csproj", "{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "CoefficientOfThermalExpansion", "UnitsNet.Modular\GeneratedCode\CoefficientOfThermalExpansion\CoefficientOfThermalExpansion.csproj", "{A9514CE6-D4E7-88CA-051E-E9E53610C519}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Compressibility", "UnitsNet.Modular\GeneratedCode\Compressibility\Compressibility.csproj", "{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Density", "UnitsNet.Modular\GeneratedCode\Density\Density.csproj", "{D683A277-5892-AEC2-985D-C2343725D0AF}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Duration", "UnitsNet.Modular\GeneratedCode\Duration\Duration.csproj", "{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "DynamicViscosity", "UnitsNet.Modular\GeneratedCode\DynamicViscosity\DynamicViscosity.csproj", "{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricAdmittance", "UnitsNet.Modular\GeneratedCode\ElectricAdmittance\ElectricAdmittance.csproj", "{2EE55C63-D077-25DD-F076-857ADFE08080}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricCharge", "UnitsNet.Modular\GeneratedCode\ElectricCharge\ElectricCharge.csproj", "{F4286CFC-484B-8466-8EFA-1111696BABB9}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricChargeDensity", "UnitsNet.Modular\GeneratedCode\ElectricChargeDensity\ElectricChargeDensity.csproj", "{B1567C85-AD77-C283-9165-777AD0E9A2EB}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricConductance", "UnitsNet.Modular\GeneratedCode\ElectricConductance\ElectricConductance.csproj", "{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricConductivity", "UnitsNet.Modular\GeneratedCode\ElectricConductivity\ElectricConductivity.csproj", "{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricCurrent", "UnitsNet.Modular\GeneratedCode\ElectricCurrent\ElectricCurrent.csproj", "{55160A70-69B2-4144-B974-B64D78BD50E0}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricCurrentDensity", "UnitsNet.Modular\GeneratedCode\ElectricCurrentDensity\ElectricCurrentDensity.csproj", "{8BEDA85E-3D20-5926-C060-F92913F1192E}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricCurrentGradient", "UnitsNet.Modular\GeneratedCode\ElectricCurrentGradient\ElectricCurrentGradient.csproj", "{29DF066C-C160-CD60-B10F-23A0C3BB8457}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricField", "UnitsNet.Modular\GeneratedCode\ElectricField\ElectricField.csproj", "{635581A6-F954-D0E4-9C68-02C1725E49D2}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricInductance", "UnitsNet.Modular\GeneratedCode\ElectricInductance\ElectricInductance.csproj", "{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricPotential", "UnitsNet.Modular\GeneratedCode\ElectricPotential\ElectricPotential.csproj", "{66C94DC2-E546-9737-A45B-4BC60FE0E536}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricPotentialAc", "UnitsNet.Modular\GeneratedCode\ElectricPotentialAc\ElectricPotentialAc.csproj", "{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricPotentialChangeRate", "UnitsNet.Modular\GeneratedCode\ElectricPotentialChangeRate\ElectricPotentialChangeRate.csproj", "{679517CA-9D0B-0EC2-35AE-95230281CFBA}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricPotentialDc", "UnitsNet.Modular\GeneratedCode\ElectricPotentialDc\ElectricPotentialDc.csproj", "{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricResistance", "UnitsNet.Modular\GeneratedCode\ElectricResistance\ElectricResistance.csproj", "{78D59E90-3339-54D6-3803-F68623B72EFF}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricResistivity", "UnitsNet.Modular\GeneratedCode\ElectricResistivity\ElectricResistivity.csproj", "{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ElectricSurfaceChargeDensity", "UnitsNet.Modular\GeneratedCode\ElectricSurfaceChargeDensity\ElectricSurfaceChargeDensity.csproj", "{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Energy", "UnitsNet.Modular\GeneratedCode\Energy\Energy.csproj", "{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "EnergyDensity", "UnitsNet.Modular\GeneratedCode\EnergyDensity\EnergyDensity.csproj", "{C5025916-5039-97C2-B450-AF1420F5FB08}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Entropy", "UnitsNet.Modular\GeneratedCode\Entropy\Entropy.csproj", "{816884BB-A5F6-5C07-967B-BB8F21D724B7}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Force", "UnitsNet.Modular\GeneratedCode\Force\Force.csproj", "{5517DACF-B1FF-6515-E5B6-B5081F92F407}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ForceChangeRate", "UnitsNet.Modular\GeneratedCode\ForceChangeRate\ForceChangeRate.csproj", "{97AD732D-4CE5-2027-AABC-844002D29C23}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ForcePerLength", "UnitsNet.Modular\GeneratedCode\ForcePerLength\ForcePerLength.csproj", "{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Frequency", "UnitsNet.Modular\GeneratedCode\Frequency\Frequency.csproj", "{8D66B616-3198-B8A1-D2D0-03496DB6A62B}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "FuelEfficiency", "UnitsNet.Modular\GeneratedCode\FuelEfficiency\FuelEfficiency.csproj", "{6E68FF9B-3947-D706-3AD7-F9237A67C874}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "HeatFlux", "UnitsNet.Modular\GeneratedCode\HeatFlux\HeatFlux.csproj", "{2B132458-96E5-72BF-673F-DDA4A7FD514B}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "HeatTransferCoefficient", "UnitsNet.Modular\GeneratedCode\HeatTransferCoefficient\HeatTransferCoefficient.csproj", "{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Illuminance", "UnitsNet.Modular\GeneratedCode\Illuminance\Illuminance.csproj", "{D846582B-8AE3-9779-01EA-7210B5330CFD}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Information", "UnitsNet.Modular\GeneratedCode\Information\Information.csproj", "{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Irradiance", "UnitsNet.Modular\GeneratedCode\Irradiance\Irradiance.csproj", "{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Irradiation", "UnitsNet.Modular\GeneratedCode\Irradiation\Irradiation.csproj", "{B545726F-7A83-3C78-2B55-6A709C5A6D00}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Jerk", "UnitsNet.Modular\GeneratedCode\Jerk\Jerk.csproj", "{8540CFB1-FE4A-DCC3-A70E-840262803CFC}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "KinematicViscosity", "UnitsNet.Modular\GeneratedCode\KinematicViscosity\KinematicViscosity.csproj", "{733E533D-9FF2-4C72-3DA9-200F758DC6E3}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Length", "UnitsNet.Modular\GeneratedCode\Length\Length.csproj", "{0556C9AD-B3A1-730C-959F-BAF21E60F972}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Level", "UnitsNet.Modular\GeneratedCode\Level\Level.csproj", "{5C300917-A99F-D166-4F56-F0DA3C3614BB}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "LinearDensity", "UnitsNet.Modular\GeneratedCode\LinearDensity\LinearDensity.csproj", "{AB414094-9582-3357-D0E9-20B153A1B54C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "LinearPowerDensity", "UnitsNet.Modular\GeneratedCode\LinearPowerDensity\LinearPowerDensity.csproj", "{8823A9EE-673A-E7D4-3C0A-BAE61A262388}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Luminance", "UnitsNet.Modular\GeneratedCode\Luminance\Luminance.csproj", "{CBDED274-6B9B-A113-D56F-00B38006CC84}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Luminosity", "UnitsNet.Modular\GeneratedCode\Luminosity\Luminosity.csproj", "{FE30ED04-094F-5005-B0AA-1B3623DB60B2}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "LuminousFlux", "UnitsNet.Modular\GeneratedCode\LuminousFlux\LuminousFlux.csproj", "{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "LuminousIntensity", "UnitsNet.Modular\GeneratedCode\LuminousIntensity\LuminousIntensity.csproj", "{733F9598-101B-936B-B081-2805DD793091}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MagneticField", "UnitsNet.Modular\GeneratedCode\MagneticField\MagneticField.csproj", "{809C4AFA-D014-471B-518B-4FD01CB7C808}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MagneticFlux", "UnitsNet.Modular\GeneratedCode\MagneticFlux\MagneticFlux.csproj", "{F0C5342B-FB95-48A4-029F-7AA631CE06F1}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Magnetization", "UnitsNet.Modular\GeneratedCode\Magnetization\Magnetization.csproj", "{3EA3301E-D3DE-6979-F1D7-58352998951C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Mass", "UnitsNet.Modular\GeneratedCode\Mass\Mass.csproj", "{F8C5A010-C353-31DA-CADC-B56186BE374F}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MassConcentration", "UnitsNet.Modular\GeneratedCode\MassConcentration\MassConcentration.csproj", "{0B1482C2-A3B1-6207-B73F-A07F46718B65}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MassFlow", "UnitsNet.Modular\GeneratedCode\MassFlow\MassFlow.csproj", "{A0821347-BE46-C587-B61D-5152C578048D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MassFlux", "UnitsNet.Modular\GeneratedCode\MassFlux\MassFlux.csproj", "{15622F39-B4C5-7E66-57BC-31900B6065C8}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MassFraction", "UnitsNet.Modular\GeneratedCode\MassFraction\MassFraction.csproj", "{DB140D08-4769-DC51-8809-A9222B830EF4}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MassMomentOfInertia", "UnitsNet.Modular\GeneratedCode\MassMomentOfInertia\MassMomentOfInertia.csproj", "{6218C061-3905-79B2-D3BC-BB7B8FC77A69}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MolarEnergy", "UnitsNet.Modular\GeneratedCode\MolarEnergy\MolarEnergy.csproj", "{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MolarEntropy", "UnitsNet.Modular\GeneratedCode\MolarEntropy\MolarEntropy.csproj", "{2053731B-90F5-5141-D15E-8D7BE8C2662F}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Molarity", "UnitsNet.Modular\GeneratedCode\Molarity\Molarity.csproj", "{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "MolarMass", "UnitsNet.Modular\GeneratedCode\MolarMass\MolarMass.csproj", "{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Permeability", "UnitsNet.Modular\GeneratedCode\Permeability\Permeability.csproj", "{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Permittivity", "UnitsNet.Modular\GeneratedCode\Permittivity\Permittivity.csproj", "{9B381685-8129-ACBA-66F0-7068FE43A6C3}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "PorousMediumPermeability", "UnitsNet.Modular\GeneratedCode\PorousMediumPermeability\PorousMediumPermeability.csproj", "{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Power", "UnitsNet.Modular\GeneratedCode\Power\Power.csproj", "{56968E84-6B7D-D548-4C0B-53017BD6123C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "PowerDensity", "UnitsNet.Modular\GeneratedCode\PowerDensity\PowerDensity.csproj", "{5E741DD9-690A-DE16-E7A1-85E6239AA70D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "PowerRatio", "UnitsNet.Modular\GeneratedCode\PowerRatio\PowerRatio.csproj", "{94317D9A-D614-B098-6175-76EE84262C05}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Pressure", "UnitsNet.Modular\GeneratedCode\Pressure\Pressure.csproj", "{F907841F-B1EE-9B12-580E-CFE2324BED03}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "PressureChangeRate", "UnitsNet.Modular\GeneratedCode\PressureChangeRate\PressureChangeRate.csproj", "{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Ratio", "UnitsNet.Modular\GeneratedCode\Ratio\Ratio.csproj", "{B0BE4813-D93E-7B06-D422-23CA28ADF22A}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "RatioChangeRate", "UnitsNet.Modular\GeneratedCode\RatioChangeRate\RatioChangeRate.csproj", "{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ReactiveEnergy", "UnitsNet.Modular\GeneratedCode\ReactiveEnergy\ReactiveEnergy.csproj", "{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ReactivePower", "UnitsNet.Modular\GeneratedCode\ReactivePower\ReactivePower.csproj", "{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ReciprocalArea", "UnitsNet.Modular\GeneratedCode\ReciprocalArea\ReciprocalArea.csproj", "{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ReciprocalLength", "UnitsNet.Modular\GeneratedCode\ReciprocalLength\ReciprocalLength.csproj", "{83D6C79A-C71A-D467-284C-28EDBBD059D2}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "RelativeHumidity", "UnitsNet.Modular\GeneratedCode\RelativeHumidity\RelativeHumidity.csproj", "{4AC05C74-08C5-2153-F38C-976975747B5C}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "RotationalAcceleration", "UnitsNet.Modular\GeneratedCode\RotationalAcceleration\RotationalAcceleration.csproj", "{E2110137-6A36-F4D1-2219-26EB18FEE74D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "RotationalSpeed", "UnitsNet.Modular\GeneratedCode\RotationalSpeed\RotationalSpeed.csproj", "{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "RotationalStiffness", "UnitsNet.Modular\GeneratedCode\RotationalStiffness\RotationalStiffness.csproj", "{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "RotationalStiffnessPerLength", "UnitsNet.Modular\GeneratedCode\RotationalStiffnessPerLength\RotationalStiffnessPerLength.csproj", "{EAE89113-1312-F83C-1A4B-638B98E760B3}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Scalar", "UnitsNet.Modular\GeneratedCode\Scalar\Scalar.csproj", "{609C8143-BDB3-709B-A7A5-CC33659C9B51}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "SolidAngle", "UnitsNet.Modular\GeneratedCode\SolidAngle\SolidAngle.csproj", "{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "SpecificEnergy", "UnitsNet.Modular\GeneratedCode\SpecificEnergy\SpecificEnergy.csproj", "{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "SpecificEntropy", "UnitsNet.Modular\GeneratedCode\SpecificEntropy\SpecificEntropy.csproj", "{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "SpecificFuelConsumption", "UnitsNet.Modular\GeneratedCode\SpecificFuelConsumption\SpecificFuelConsumption.csproj", "{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "SpecificVolume", "UnitsNet.Modular\GeneratedCode\SpecificVolume\SpecificVolume.csproj", "{74B88D5C-96E5-7286-D2B2-8DEF18538246}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "SpecificWeight", "UnitsNet.Modular\GeneratedCode\SpecificWeight\SpecificWeight.csproj", "{D63AC796-7087-BF6C-2848-E6511358FBE4}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Speed", "UnitsNet.Modular\GeneratedCode\Speed\Speed.csproj", "{E9FE72C3-56B4-856B-A592-AE6E98E571F3}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "StandardVolumeFlow", "UnitsNet.Modular\GeneratedCode\StandardVolumeFlow\StandardVolumeFlow.csproj", "{5DA7DBE9-F180-570F-2DA0-2737F043744D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Temperature", "UnitsNet.Modular\GeneratedCode\Temperature\Temperature.csproj", "{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "TemperatureChangeRate", "UnitsNet.Modular\GeneratedCode\TemperatureChangeRate\TemperatureChangeRate.csproj", "{DFBB7B9F-C604-FEDD-E658-17E196043123}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "TemperatureDelta", "UnitsNet.Modular\GeneratedCode\TemperatureDelta\TemperatureDelta.csproj", "{8854C5E8-E40B-74C3-AAFC-DE0F13239276}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "TemperatureGradient", "UnitsNet.Modular\GeneratedCode\TemperatureGradient\TemperatureGradient.csproj", "{83D1D75E-3C26-B8D0-F097-F99452E749CC}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ThermalConductivity", "UnitsNet.Modular\GeneratedCode\ThermalConductivity\ThermalConductivity.csproj", "{7E7D8010-B37A-151A-11A5-1DB234EE1104}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "ThermalResistance", "UnitsNet.Modular\GeneratedCode\ThermalResistance\ThermalResistance.csproj", "{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Torque", "UnitsNet.Modular\GeneratedCode\Torque\Torque.csproj", "{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "TorquePerLength", "UnitsNet.Modular\GeneratedCode\TorquePerLength\TorquePerLength.csproj", "{C27E1919-64F1-CE81-C6D9-B46CED745A12}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Turbidity", "UnitsNet.Modular\GeneratedCode\Turbidity\Turbidity.csproj", "{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "VitaminA", "UnitsNet.Modular\GeneratedCode\VitaminA\VitaminA.csproj", "{C00185AF-8735-7674-5FA6-232424B04161}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "Volume", "UnitsNet.Modular\GeneratedCode\Volume\Volume.csproj", "{66B90FB1-20D7-F563-3477-4C7C6B404F4D}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "VolumeConcentration", "UnitsNet.Modular\GeneratedCode\VolumeConcentration\VolumeConcentration.csproj", "{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "VolumeFlow", "UnitsNet.Modular\GeneratedCode\VolumeFlow\VolumeFlow.csproj", "{B22E47E1-9506-56E6-3D19-780B887D8CB3}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "VolumeFlowPerArea", "UnitsNet.Modular\GeneratedCode\VolumeFlowPerArea\VolumeFlowPerArea.csproj", "{753BCC52-C451-8B29-6AE7-520B02EE6960}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "VolumePerLength", "UnitsNet.Modular\GeneratedCode\VolumePerLength\VolumePerLength.csproj", "{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "VolumetricHeatCapacity", "UnitsNet.Modular\GeneratedCode\VolumetricHeatCapacity\VolumetricHeatCapacity.csproj", "{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "WarpingMomentOfInertia", "UnitsNet.Modular\GeneratedCode\WarpingMomentOfInertia\WarpingMomentOfInertia.csproj", "{8433AAC6-218D-9B7B-6EAA-36774E165446}" +EndProject +Project("{660E8A78-57A3-4365-B7B5-336A552181CE}") = "UnitsNet.Core", "UnitsNet.Core\UnitsNet.Core.csproj", "{B17CAC44-10AB-3221-0495-61686C515AE8}" +EndProject +Global + GlobalSection(ProjectConfigurationPlatforms) = postSolution + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution +{8E3A6691-A05F-D71C-F12A-F537C0807F85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8E3A6691-A05F-D71C-F12A-F537C0807F85}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8E3A6691-A05F-D71C-F12A-F537C0807F85}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8E3A6691-A05F-D71C-F12A-F537C0807F85}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8E3A6691-A05F-D71C-F12A-F537C0807F85}.Release|Any CPU.Build.0 = Release|Any CPU +{8E3A6691-A05F-D71C-F12A-F537C0807F85}.Release|Any CPU.Deploy.0 = Release|Any CPU +{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Release|Any CPU.Build.0 = Release|Any CPU +{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{59C09A1B-EFF0-E367-6372-D16C4C984916}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{59C09A1B-EFF0-E367-6372-D16C4C984916}.Debug|Any CPU.Build.0 = Debug|Any CPU +{59C09A1B-EFF0-E367-6372-D16C4C984916}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{59C09A1B-EFF0-E367-6372-D16C4C984916}.Release|Any CPU.ActiveCfg = Release|Any CPU +{59C09A1B-EFF0-E367-6372-D16C4C984916}.Release|Any CPU.Build.0 = Release|Any CPU +{59C09A1B-EFF0-E367-6372-D16C4C984916}.Release|Any CPU.Deploy.0 = Release|Any CPU +{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}.Debug|Any CPU.Build.0 = Debug|Any CPU +{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}.Release|Any CPU.ActiveCfg = Release|Any CPU +{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}.Release|Any CPU.Build.0 = Release|Any CPU +{4B036819-F813-0C4D-3E44-1FCC8B5F3EC7}.Release|Any CPU.Deploy.0 = Release|Any CPU +{6F80E841-E953-BC39-6670-8711F2AD9D18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{6F80E841-E953-BC39-6670-8711F2AD9D18}.Debug|Any CPU.Build.0 = Debug|Any CPU +{6F80E841-E953-BC39-6670-8711F2AD9D18}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{6F80E841-E953-BC39-6670-8711F2AD9D18}.Release|Any CPU.ActiveCfg = Release|Any CPU +{6F80E841-E953-BC39-6670-8711F2AD9D18}.Release|Any CPU.Build.0 = Release|Any CPU +{6F80E841-E953-BC39-6670-8711F2AD9D18}.Release|Any CPU.Deploy.0 = Release|Any CPU +{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}.Debug|Any CPU.Build.0 = Debug|Any CPU +{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}.Release|Any CPU.ActiveCfg = Release|Any CPU +{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}.Release|Any CPU.Build.0 = Release|Any CPU +{88B9A61A-B21B-97CC-EF89-78D1E3FF7767}.Release|Any CPU.Deploy.0 = Release|Any CPU +{04C24D02-BAD7-A877-FF9B-A36A886C9633}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{04C24D02-BAD7-A877-FF9B-A36A886C9633}.Debug|Any CPU.Build.0 = Debug|Any CPU +{04C24D02-BAD7-A877-FF9B-A36A886C9633}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{04C24D02-BAD7-A877-FF9B-A36A886C9633}.Release|Any CPU.ActiveCfg = Release|Any CPU +{04C24D02-BAD7-A877-FF9B-A36A886C9633}.Release|Any CPU.Build.0 = Release|Any CPU +{04C24D02-BAD7-A877-FF9B-A36A886C9633}.Release|Any CPU.Deploy.0 = Release|Any CPU +{92FF1332-BF34-943E-A58D-8A76746D879E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{92FF1332-BF34-943E-A58D-8A76746D879E}.Debug|Any CPU.Build.0 = Debug|Any CPU +{92FF1332-BF34-943E-A58D-8A76746D879E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{92FF1332-BF34-943E-A58D-8A76746D879E}.Release|Any CPU.ActiveCfg = Release|Any CPU +{92FF1332-BF34-943E-A58D-8A76746D879E}.Release|Any CPU.Build.0 = Release|Any CPU +{92FF1332-BF34-943E-A58D-8A76746D879E}.Release|Any CPU.Deploy.0 = Release|Any CPU +{566EF13C-0D17-E465-D35F-1BD9C65559BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{566EF13C-0D17-E465-D35F-1BD9C65559BF}.Debug|Any CPU.Build.0 = Debug|Any CPU +{566EF13C-0D17-E465-D35F-1BD9C65559BF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{566EF13C-0D17-E465-D35F-1BD9C65559BF}.Release|Any CPU.ActiveCfg = Release|Any CPU +{566EF13C-0D17-E465-D35F-1BD9C65559BF}.Release|Any CPU.Build.0 = Release|Any CPU +{566EF13C-0D17-E465-D35F-1BD9C65559BF}.Release|Any CPU.Deploy.0 = Release|Any CPU +{B5FDF997-829F-5281-E624-EE4EEE5AA26C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B5FDF997-829F-5281-E624-EE4EEE5AA26C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B5FDF997-829F-5281-E624-EE4EEE5AA26C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{B5FDF997-829F-5281-E624-EE4EEE5AA26C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B5FDF997-829F-5281-E624-EE4EEE5AA26C}.Release|Any CPU.Build.0 = Release|Any CPU +{B5FDF997-829F-5281-E624-EE4EEE5AA26C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{085145F2-2B8F-4D09-5290-C14CDCD452BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{085145F2-2B8F-4D09-5290-C14CDCD452BF}.Debug|Any CPU.Build.0 = Debug|Any CPU +{085145F2-2B8F-4D09-5290-C14CDCD452BF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{085145F2-2B8F-4D09-5290-C14CDCD452BF}.Release|Any CPU.ActiveCfg = Release|Any CPU +{085145F2-2B8F-4D09-5290-C14CDCD452BF}.Release|Any CPU.Build.0 = Release|Any CPU +{085145F2-2B8F-4D09-5290-C14CDCD452BF}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}.Release|Any CPU.Build.0 = Release|Any CPU +{C1351FC7-D3D8-C3CE-0715-AD8E18AB8C94}.Release|Any CPU.Deploy.0 = Release|Any CPU +{A9514CE6-D4E7-88CA-051E-E9E53610C519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{A9514CE6-D4E7-88CA-051E-E9E53610C519}.Debug|Any CPU.Build.0 = Debug|Any CPU +{A9514CE6-D4E7-88CA-051E-E9E53610C519}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{A9514CE6-D4E7-88CA-051E-E9E53610C519}.Release|Any CPU.ActiveCfg = Release|Any CPU +{A9514CE6-D4E7-88CA-051E-E9E53610C519}.Release|Any CPU.Build.0 = Release|Any CPU +{A9514CE6-D4E7-88CA-051E-E9E53610C519}.Release|Any CPU.Deploy.0 = Release|Any CPU +{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}.Debug|Any CPU.Build.0 = Debug|Any CPU +{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}.Release|Any CPU.ActiveCfg = Release|Any CPU +{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}.Release|Any CPU.Build.0 = Release|Any CPU +{DAF647BE-BE87-88B9-EE92-DECE21FE0DFF}.Release|Any CPU.Deploy.0 = Release|Any CPU +{D683A277-5892-AEC2-985D-C2343725D0AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{D683A277-5892-AEC2-985D-C2343725D0AF}.Debug|Any CPU.Build.0 = Debug|Any CPU +{D683A277-5892-AEC2-985D-C2343725D0AF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{D683A277-5892-AEC2-985D-C2343725D0AF}.Release|Any CPU.ActiveCfg = Release|Any CPU +{D683A277-5892-AEC2-985D-C2343725D0AF}.Release|Any CPU.Build.0 = Release|Any CPU +{D683A277-5892-AEC2-985D-C2343725D0AF}.Release|Any CPU.Deploy.0 = Release|Any CPU +{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Debug|Any CPU.Build.0 = Debug|Any CPU +{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Release|Any CPU.ActiveCfg = Release|Any CPU +{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Release|Any CPU.Build.0 = Release|Any CPU +{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}.Release|Any CPU.Build.0 = Release|Any CPU +{5DDE57F4-3F98-C4B7-47E5-65229FAF1F0F}.Release|Any CPU.Deploy.0 = Release|Any CPU +{2EE55C63-D077-25DD-F076-857ADFE08080}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{2EE55C63-D077-25DD-F076-857ADFE08080}.Debug|Any CPU.Build.0 = Debug|Any CPU +{2EE55C63-D077-25DD-F076-857ADFE08080}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{2EE55C63-D077-25DD-F076-857ADFE08080}.Release|Any CPU.ActiveCfg = Release|Any CPU +{2EE55C63-D077-25DD-F076-857ADFE08080}.Release|Any CPU.Build.0 = Release|Any CPU +{2EE55C63-D077-25DD-F076-857ADFE08080}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F4286CFC-484B-8466-8EFA-1111696BABB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F4286CFC-484B-8466-8EFA-1111696BABB9}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F4286CFC-484B-8466-8EFA-1111696BABB9}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F4286CFC-484B-8466-8EFA-1111696BABB9}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F4286CFC-484B-8466-8EFA-1111696BABB9}.Release|Any CPU.Build.0 = Release|Any CPU +{F4286CFC-484B-8466-8EFA-1111696BABB9}.Release|Any CPU.Deploy.0 = Release|Any CPU +{B1567C85-AD77-C283-9165-777AD0E9A2EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B1567C85-AD77-C283-9165-777AD0E9A2EB}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B1567C85-AD77-C283-9165-777AD0E9A2EB}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{B1567C85-AD77-C283-9165-777AD0E9A2EB}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B1567C85-AD77-C283-9165-777AD0E9A2EB}.Release|Any CPU.Build.0 = Release|Any CPU +{B1567C85-AD77-C283-9165-777AD0E9A2EB}.Release|Any CPU.Deploy.0 = Release|Any CPU +{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}.Release|Any CPU.Build.0 = Release|Any CPU +{FCD3DFB2-9EE2-AD22-0E1F-4CDDD575792A}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}.Release|Any CPU.Build.0 = Release|Any CPU +{F420ECCC-B12D-72E4-2AD2-F93054EEEC30}.Release|Any CPU.Deploy.0 = Release|Any CPU +{55160A70-69B2-4144-B974-B64D78BD50E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{55160A70-69B2-4144-B974-B64D78BD50E0}.Debug|Any CPU.Build.0 = Debug|Any CPU +{55160A70-69B2-4144-B974-B64D78BD50E0}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{55160A70-69B2-4144-B974-B64D78BD50E0}.Release|Any CPU.ActiveCfg = Release|Any CPU +{55160A70-69B2-4144-B974-B64D78BD50E0}.Release|Any CPU.Build.0 = Release|Any CPU +{55160A70-69B2-4144-B974-B64D78BD50E0}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8BEDA85E-3D20-5926-C060-F92913F1192E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8BEDA85E-3D20-5926-C060-F92913F1192E}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8BEDA85E-3D20-5926-C060-F92913F1192E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8BEDA85E-3D20-5926-C060-F92913F1192E}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8BEDA85E-3D20-5926-C060-F92913F1192E}.Release|Any CPU.Build.0 = Release|Any CPU +{8BEDA85E-3D20-5926-C060-F92913F1192E}.Release|Any CPU.Deploy.0 = Release|Any CPU +{29DF066C-C160-CD60-B10F-23A0C3BB8457}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{29DF066C-C160-CD60-B10F-23A0C3BB8457}.Debug|Any CPU.Build.0 = Debug|Any CPU +{29DF066C-C160-CD60-B10F-23A0C3BB8457}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{29DF066C-C160-CD60-B10F-23A0C3BB8457}.Release|Any CPU.ActiveCfg = Release|Any CPU +{29DF066C-C160-CD60-B10F-23A0C3BB8457}.Release|Any CPU.Build.0 = Release|Any CPU +{29DF066C-C160-CD60-B10F-23A0C3BB8457}.Release|Any CPU.Deploy.0 = Release|Any CPU +{635581A6-F954-D0E4-9C68-02C1725E49D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{635581A6-F954-D0E4-9C68-02C1725E49D2}.Debug|Any CPU.Build.0 = Debug|Any CPU +{635581A6-F954-D0E4-9C68-02C1725E49D2}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{635581A6-F954-D0E4-9C68-02C1725E49D2}.Release|Any CPU.ActiveCfg = Release|Any CPU +{635581A6-F954-D0E4-9C68-02C1725E49D2}.Release|Any CPU.Build.0 = Release|Any CPU +{635581A6-F954-D0E4-9C68-02C1725E49D2}.Release|Any CPU.Deploy.0 = Release|Any CPU +{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}.Debug|Any CPU.Build.0 = Debug|Any CPU +{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}.Release|Any CPU.ActiveCfg = Release|Any CPU +{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}.Release|Any CPU.Build.0 = Release|Any CPU +{76BF8A97-E573-A5B5-286F-04CA7E00F8E9}.Release|Any CPU.Deploy.0 = Release|Any CPU +{66C94DC2-E546-9737-A45B-4BC60FE0E536}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{66C94DC2-E546-9737-A45B-4BC60FE0E536}.Debug|Any CPU.Build.0 = Debug|Any CPU +{66C94DC2-E546-9737-A45B-4BC60FE0E536}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{66C94DC2-E546-9737-A45B-4BC60FE0E536}.Release|Any CPU.ActiveCfg = Release|Any CPU +{66C94DC2-E546-9737-A45B-4BC60FE0E536}.Release|Any CPU.Build.0 = Release|Any CPU +{66C94DC2-E546-9737-A45B-4BC60FE0E536}.Release|Any CPU.Deploy.0 = Release|Any CPU +{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}.Release|Any CPU.Build.0 = Release|Any CPU +{AB1339EC-F1D8-6ABF-093E-1525EE231A9D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{679517CA-9D0B-0EC2-35AE-95230281CFBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{679517CA-9D0B-0EC2-35AE-95230281CFBA}.Debug|Any CPU.Build.0 = Debug|Any CPU +{679517CA-9D0B-0EC2-35AE-95230281CFBA}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{679517CA-9D0B-0EC2-35AE-95230281CFBA}.Release|Any CPU.ActiveCfg = Release|Any CPU +{679517CA-9D0B-0EC2-35AE-95230281CFBA}.Release|Any CPU.Build.0 = Release|Any CPU +{679517CA-9D0B-0EC2-35AE-95230281CFBA}.Release|Any CPU.Deploy.0 = Release|Any CPU +{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}.Release|Any CPU.Build.0 = Release|Any CPU +{27EBF863-3EE7-DDB0-08AB-8577438A8F1C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{78D59E90-3339-54D6-3803-F68623B72EFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{78D59E90-3339-54D6-3803-F68623B72EFF}.Debug|Any CPU.Build.0 = Debug|Any CPU +{78D59E90-3339-54D6-3803-F68623B72EFF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{78D59E90-3339-54D6-3803-F68623B72EFF}.Release|Any CPU.ActiveCfg = Release|Any CPU +{78D59E90-3339-54D6-3803-F68623B72EFF}.Release|Any CPU.Build.0 = Release|Any CPU +{78D59E90-3339-54D6-3803-F68623B72EFF}.Release|Any CPU.Deploy.0 = Release|Any CPU +{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}.Release|Any CPU.Build.0 = Release|Any CPU +{6A4A0F45-C2B4-6BE4-E44A-E78D3282359F}.Release|Any CPU.Deploy.0 = Release|Any CPU +{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}.Release|Any CPU.Build.0 = Release|Any CPU +{006E161D-AAE1-2DD1-5B94-EBD45D31F50A}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}.Release|Any CPU.Build.0 = Release|Any CPU +{F7D3FCF2-CADC-19DD-4C4C-5A54A5102C95}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C5025916-5039-97C2-B450-AF1420F5FB08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C5025916-5039-97C2-B450-AF1420F5FB08}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C5025916-5039-97C2-B450-AF1420F5FB08}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C5025916-5039-97C2-B450-AF1420F5FB08}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C5025916-5039-97C2-B450-AF1420F5FB08}.Release|Any CPU.Build.0 = Release|Any CPU +{C5025916-5039-97C2-B450-AF1420F5FB08}.Release|Any CPU.Deploy.0 = Release|Any CPU +{816884BB-A5F6-5C07-967B-BB8F21D724B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{816884BB-A5F6-5C07-967B-BB8F21D724B7}.Debug|Any CPU.Build.0 = Debug|Any CPU +{816884BB-A5F6-5C07-967B-BB8F21D724B7}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{816884BB-A5F6-5C07-967B-BB8F21D724B7}.Release|Any CPU.ActiveCfg = Release|Any CPU +{816884BB-A5F6-5C07-967B-BB8F21D724B7}.Release|Any CPU.Build.0 = Release|Any CPU +{816884BB-A5F6-5C07-967B-BB8F21D724B7}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5517DACF-B1FF-6515-E5B6-B5081F92F407}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5517DACF-B1FF-6515-E5B6-B5081F92F407}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5517DACF-B1FF-6515-E5B6-B5081F92F407}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5517DACF-B1FF-6515-E5B6-B5081F92F407}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5517DACF-B1FF-6515-E5B6-B5081F92F407}.Release|Any CPU.Build.0 = Release|Any CPU +{5517DACF-B1FF-6515-E5B6-B5081F92F407}.Release|Any CPU.Deploy.0 = Release|Any CPU +{97AD732D-4CE5-2027-AABC-844002D29C23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{97AD732D-4CE5-2027-AABC-844002D29C23}.Debug|Any CPU.Build.0 = Debug|Any CPU +{97AD732D-4CE5-2027-AABC-844002D29C23}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{97AD732D-4CE5-2027-AABC-844002D29C23}.Release|Any CPU.ActiveCfg = Release|Any CPU +{97AD732D-4CE5-2027-AABC-844002D29C23}.Release|Any CPU.Build.0 = Release|Any CPU +{97AD732D-4CE5-2027-AABC-844002D29C23}.Release|Any CPU.Deploy.0 = Release|Any CPU +{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}.Debug|Any CPU.Build.0 = Debug|Any CPU +{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}.Release|Any CPU.ActiveCfg = Release|Any CPU +{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}.Release|Any CPU.Build.0 = Release|Any CPU +{6B975D30-C5DD-F1FD-9D0C-4D56ECDF9B25}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8D66B616-3198-B8A1-D2D0-03496DB6A62B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8D66B616-3198-B8A1-D2D0-03496DB6A62B}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8D66B616-3198-B8A1-D2D0-03496DB6A62B}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8D66B616-3198-B8A1-D2D0-03496DB6A62B}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8D66B616-3198-B8A1-D2D0-03496DB6A62B}.Release|Any CPU.Build.0 = Release|Any CPU +{8D66B616-3198-B8A1-D2D0-03496DB6A62B}.Release|Any CPU.Deploy.0 = Release|Any CPU +{6E68FF9B-3947-D706-3AD7-F9237A67C874}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{6E68FF9B-3947-D706-3AD7-F9237A67C874}.Debug|Any CPU.Build.0 = Debug|Any CPU +{6E68FF9B-3947-D706-3AD7-F9237A67C874}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{6E68FF9B-3947-D706-3AD7-F9237A67C874}.Release|Any CPU.ActiveCfg = Release|Any CPU +{6E68FF9B-3947-D706-3AD7-F9237A67C874}.Release|Any CPU.Build.0 = Release|Any CPU +{6E68FF9B-3947-D706-3AD7-F9237A67C874}.Release|Any CPU.Deploy.0 = Release|Any CPU +{2B132458-96E5-72BF-673F-DDA4A7FD514B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{2B132458-96E5-72BF-673F-DDA4A7FD514B}.Debug|Any CPU.Build.0 = Debug|Any CPU +{2B132458-96E5-72BF-673F-DDA4A7FD514B}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{2B132458-96E5-72BF-673F-DDA4A7FD514B}.Release|Any CPU.ActiveCfg = Release|Any CPU +{2B132458-96E5-72BF-673F-DDA4A7FD514B}.Release|Any CPU.Build.0 = Release|Any CPU +{2B132458-96E5-72BF-673F-DDA4A7FD514B}.Release|Any CPU.Deploy.0 = Release|Any CPU +{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}.Debug|Any CPU.Build.0 = Debug|Any CPU +{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}.Release|Any CPU.ActiveCfg = Release|Any CPU +{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}.Release|Any CPU.Build.0 = Release|Any CPU +{3EDE821E-EE76-967E-94D7-5B1D1239C8DD}.Release|Any CPU.Deploy.0 = Release|Any CPU +{D846582B-8AE3-9779-01EA-7210B5330CFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{D846582B-8AE3-9779-01EA-7210B5330CFD}.Debug|Any CPU.Build.0 = Debug|Any CPU +{D846582B-8AE3-9779-01EA-7210B5330CFD}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{D846582B-8AE3-9779-01EA-7210B5330CFD}.Release|Any CPU.ActiveCfg = Release|Any CPU +{D846582B-8AE3-9779-01EA-7210B5330CFD}.Release|Any CPU.Build.0 = Release|Any CPU +{D846582B-8AE3-9779-01EA-7210B5330CFD}.Release|Any CPU.Deploy.0 = Release|Any CPU +{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}.Debug|Any CPU.Build.0 = Debug|Any CPU +{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}.Release|Any CPU.ActiveCfg = Release|Any CPU +{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}.Release|Any CPU.Build.0 = Release|Any CPU +{12BAB01C-845F-82C9-B00B-A3639CDFB2CE}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}.Release|Any CPU.Build.0 = Release|Any CPU +{5F9C09C7-9E32-8927-7A5D-90001CEFFC69}.Release|Any CPU.Deploy.0 = Release|Any CPU +{B545726F-7A83-3C78-2B55-6A709C5A6D00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B545726F-7A83-3C78-2B55-6A709C5A6D00}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B545726F-7A83-3C78-2B55-6A709C5A6D00}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{B545726F-7A83-3C78-2B55-6A709C5A6D00}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B545726F-7A83-3C78-2B55-6A709C5A6D00}.Release|Any CPU.Build.0 = Release|Any CPU +{B545726F-7A83-3C78-2B55-6A709C5A6D00}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8540CFB1-FE4A-DCC3-A70E-840262803CFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8540CFB1-FE4A-DCC3-A70E-840262803CFC}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8540CFB1-FE4A-DCC3-A70E-840262803CFC}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8540CFB1-FE4A-DCC3-A70E-840262803CFC}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8540CFB1-FE4A-DCC3-A70E-840262803CFC}.Release|Any CPU.Build.0 = Release|Any CPU +{8540CFB1-FE4A-DCC3-A70E-840262803CFC}.Release|Any CPU.Deploy.0 = Release|Any CPU +{733E533D-9FF2-4C72-3DA9-200F758DC6E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{733E533D-9FF2-4C72-3DA9-200F758DC6E3}.Debug|Any CPU.Build.0 = Debug|Any CPU +{733E533D-9FF2-4C72-3DA9-200F758DC6E3}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{733E533D-9FF2-4C72-3DA9-200F758DC6E3}.Release|Any CPU.ActiveCfg = Release|Any CPU +{733E533D-9FF2-4C72-3DA9-200F758DC6E3}.Release|Any CPU.Build.0 = Release|Any CPU +{733E533D-9FF2-4C72-3DA9-200F758DC6E3}.Release|Any CPU.Deploy.0 = Release|Any CPU +{0556C9AD-B3A1-730C-959F-BAF21E60F972}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{0556C9AD-B3A1-730C-959F-BAF21E60F972}.Debug|Any CPU.Build.0 = Debug|Any CPU +{0556C9AD-B3A1-730C-959F-BAF21E60F972}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{0556C9AD-B3A1-730C-959F-BAF21E60F972}.Release|Any CPU.ActiveCfg = Release|Any CPU +{0556C9AD-B3A1-730C-959F-BAF21E60F972}.Release|Any CPU.Build.0 = Release|Any CPU +{0556C9AD-B3A1-730C-959F-BAF21E60F972}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5C300917-A99F-D166-4F56-F0DA3C3614BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5C300917-A99F-D166-4F56-F0DA3C3614BB}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5C300917-A99F-D166-4F56-F0DA3C3614BB}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5C300917-A99F-D166-4F56-F0DA3C3614BB}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5C300917-A99F-D166-4F56-F0DA3C3614BB}.Release|Any CPU.Build.0 = Release|Any CPU +{5C300917-A99F-D166-4F56-F0DA3C3614BB}.Release|Any CPU.Deploy.0 = Release|Any CPU +{AB414094-9582-3357-D0E9-20B153A1B54C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{AB414094-9582-3357-D0E9-20B153A1B54C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{AB414094-9582-3357-D0E9-20B153A1B54C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{AB414094-9582-3357-D0E9-20B153A1B54C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{AB414094-9582-3357-D0E9-20B153A1B54C}.Release|Any CPU.Build.0 = Release|Any CPU +{AB414094-9582-3357-D0E9-20B153A1B54C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8823A9EE-673A-E7D4-3C0A-BAE61A262388}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8823A9EE-673A-E7D4-3C0A-BAE61A262388}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8823A9EE-673A-E7D4-3C0A-BAE61A262388}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8823A9EE-673A-E7D4-3C0A-BAE61A262388}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8823A9EE-673A-E7D4-3C0A-BAE61A262388}.Release|Any CPU.Build.0 = Release|Any CPU +{8823A9EE-673A-E7D4-3C0A-BAE61A262388}.Release|Any CPU.Deploy.0 = Release|Any CPU +{CBDED274-6B9B-A113-D56F-00B38006CC84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{CBDED274-6B9B-A113-D56F-00B38006CC84}.Debug|Any CPU.Build.0 = Debug|Any CPU +{CBDED274-6B9B-A113-D56F-00B38006CC84}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{CBDED274-6B9B-A113-D56F-00B38006CC84}.Release|Any CPU.ActiveCfg = Release|Any CPU +{CBDED274-6B9B-A113-D56F-00B38006CC84}.Release|Any CPU.Build.0 = Release|Any CPU +{CBDED274-6B9B-A113-D56F-00B38006CC84}.Release|Any CPU.Deploy.0 = Release|Any CPU +{FE30ED04-094F-5005-B0AA-1B3623DB60B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{FE30ED04-094F-5005-B0AA-1B3623DB60B2}.Debug|Any CPU.Build.0 = Debug|Any CPU +{FE30ED04-094F-5005-B0AA-1B3623DB60B2}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{FE30ED04-094F-5005-B0AA-1B3623DB60B2}.Release|Any CPU.ActiveCfg = Release|Any CPU +{FE30ED04-094F-5005-B0AA-1B3623DB60B2}.Release|Any CPU.Build.0 = Release|Any CPU +{FE30ED04-094F-5005-B0AA-1B3623DB60B2}.Release|Any CPU.Deploy.0 = Release|Any CPU +{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}.Debug|Any CPU.Build.0 = Debug|Any CPU +{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}.Release|Any CPU.ActiveCfg = Release|Any CPU +{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}.Release|Any CPU.Build.0 = Release|Any CPU +{A38E4DA2-F05F-AA6F-82F1-56CD2E062D96}.Release|Any CPU.Deploy.0 = Release|Any CPU +{733F9598-101B-936B-B081-2805DD793091}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{733F9598-101B-936B-B081-2805DD793091}.Debug|Any CPU.Build.0 = Debug|Any CPU +{733F9598-101B-936B-B081-2805DD793091}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{733F9598-101B-936B-B081-2805DD793091}.Release|Any CPU.ActiveCfg = Release|Any CPU +{733F9598-101B-936B-B081-2805DD793091}.Release|Any CPU.Build.0 = Release|Any CPU +{733F9598-101B-936B-B081-2805DD793091}.Release|Any CPU.Deploy.0 = Release|Any CPU +{809C4AFA-D014-471B-518B-4FD01CB7C808}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{809C4AFA-D014-471B-518B-4FD01CB7C808}.Debug|Any CPU.Build.0 = Debug|Any CPU +{809C4AFA-D014-471B-518B-4FD01CB7C808}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{809C4AFA-D014-471B-518B-4FD01CB7C808}.Release|Any CPU.ActiveCfg = Release|Any CPU +{809C4AFA-D014-471B-518B-4FD01CB7C808}.Release|Any CPU.Build.0 = Release|Any CPU +{809C4AFA-D014-471B-518B-4FD01CB7C808}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F0C5342B-FB95-48A4-029F-7AA631CE06F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F0C5342B-FB95-48A4-029F-7AA631CE06F1}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F0C5342B-FB95-48A4-029F-7AA631CE06F1}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F0C5342B-FB95-48A4-029F-7AA631CE06F1}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F0C5342B-FB95-48A4-029F-7AA631CE06F1}.Release|Any CPU.Build.0 = Release|Any CPU +{F0C5342B-FB95-48A4-029F-7AA631CE06F1}.Release|Any CPU.Deploy.0 = Release|Any CPU +{3EA3301E-D3DE-6979-F1D7-58352998951C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{3EA3301E-D3DE-6979-F1D7-58352998951C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{3EA3301E-D3DE-6979-F1D7-58352998951C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{3EA3301E-D3DE-6979-F1D7-58352998951C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{3EA3301E-D3DE-6979-F1D7-58352998951C}.Release|Any CPU.Build.0 = Release|Any CPU +{3EA3301E-D3DE-6979-F1D7-58352998951C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F8C5A010-C353-31DA-CADC-B56186BE374F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F8C5A010-C353-31DA-CADC-B56186BE374F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F8C5A010-C353-31DA-CADC-B56186BE374F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F8C5A010-C353-31DA-CADC-B56186BE374F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F8C5A010-C353-31DA-CADC-B56186BE374F}.Release|Any CPU.Build.0 = Release|Any CPU +{F8C5A010-C353-31DA-CADC-B56186BE374F}.Release|Any CPU.Deploy.0 = Release|Any CPU +{0B1482C2-A3B1-6207-B73F-A07F46718B65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{0B1482C2-A3B1-6207-B73F-A07F46718B65}.Debug|Any CPU.Build.0 = Debug|Any CPU +{0B1482C2-A3B1-6207-B73F-A07F46718B65}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{0B1482C2-A3B1-6207-B73F-A07F46718B65}.Release|Any CPU.ActiveCfg = Release|Any CPU +{0B1482C2-A3B1-6207-B73F-A07F46718B65}.Release|Any CPU.Build.0 = Release|Any CPU +{0B1482C2-A3B1-6207-B73F-A07F46718B65}.Release|Any CPU.Deploy.0 = Release|Any CPU +{A0821347-BE46-C587-B61D-5152C578048D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{A0821347-BE46-C587-B61D-5152C578048D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{A0821347-BE46-C587-B61D-5152C578048D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{A0821347-BE46-C587-B61D-5152C578048D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{A0821347-BE46-C587-B61D-5152C578048D}.Release|Any CPU.Build.0 = Release|Any CPU +{A0821347-BE46-C587-B61D-5152C578048D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{15622F39-B4C5-7E66-57BC-31900B6065C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{15622F39-B4C5-7E66-57BC-31900B6065C8}.Debug|Any CPU.Build.0 = Debug|Any CPU +{15622F39-B4C5-7E66-57BC-31900B6065C8}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{15622F39-B4C5-7E66-57BC-31900B6065C8}.Release|Any CPU.ActiveCfg = Release|Any CPU +{15622F39-B4C5-7E66-57BC-31900B6065C8}.Release|Any CPU.Build.0 = Release|Any CPU +{15622F39-B4C5-7E66-57BC-31900B6065C8}.Release|Any CPU.Deploy.0 = Release|Any CPU +{DB140D08-4769-DC51-8809-A9222B830EF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{DB140D08-4769-DC51-8809-A9222B830EF4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{DB140D08-4769-DC51-8809-A9222B830EF4}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{DB140D08-4769-DC51-8809-A9222B830EF4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{DB140D08-4769-DC51-8809-A9222B830EF4}.Release|Any CPU.Build.0 = Release|Any CPU +{DB140D08-4769-DC51-8809-A9222B830EF4}.Release|Any CPU.Deploy.0 = Release|Any CPU +{6218C061-3905-79B2-D3BC-BB7B8FC77A69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{6218C061-3905-79B2-D3BC-BB7B8FC77A69}.Debug|Any CPU.Build.0 = Debug|Any CPU +{6218C061-3905-79B2-D3BC-BB7B8FC77A69}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{6218C061-3905-79B2-D3BC-BB7B8FC77A69}.Release|Any CPU.ActiveCfg = Release|Any CPU +{6218C061-3905-79B2-D3BC-BB7B8FC77A69}.Release|Any CPU.Build.0 = Release|Any CPU +{6218C061-3905-79B2-D3BC-BB7B8FC77A69}.Release|Any CPU.Deploy.0 = Release|Any CPU +{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}.Debug|Any CPU.Build.0 = Debug|Any CPU +{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}.Release|Any CPU.ActiveCfg = Release|Any CPU +{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}.Release|Any CPU.Build.0 = Release|Any CPU +{9B77D4E0-863D-4A74-C30A-56F7B2BB7CB7}.Release|Any CPU.Deploy.0 = Release|Any CPU +{2053731B-90F5-5141-D15E-8D7BE8C2662F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{2053731B-90F5-5141-D15E-8D7BE8C2662F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{2053731B-90F5-5141-D15E-8D7BE8C2662F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{2053731B-90F5-5141-D15E-8D7BE8C2662F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{2053731B-90F5-5141-D15E-8D7BE8C2662F}.Release|Any CPU.Build.0 = Release|Any CPU +{2053731B-90F5-5141-D15E-8D7BE8C2662F}.Release|Any CPU.Deploy.0 = Release|Any CPU +{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}.Debug|Any CPU.Build.0 = Debug|Any CPU +{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}.Release|Any CPU.ActiveCfg = Release|Any CPU +{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}.Release|Any CPU.Build.0 = Release|Any CPU +{0D21F127-8C25-9B3A-9612-CE2EEA6E7AC1}.Release|Any CPU.Deploy.0 = Release|Any CPU +{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}.Debug|Any CPU.Build.0 = Debug|Any CPU +{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}.Release|Any CPU.ActiveCfg = Release|Any CPU +{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}.Release|Any CPU.Build.0 = Release|Any CPU +{FE51BBDA-2039-23FD-F29A-39C14ADCB1F6}.Release|Any CPU.Deploy.0 = Release|Any CPU +{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}.Debug|Any CPU.Build.0 = Debug|Any CPU +{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}.Release|Any CPU.ActiveCfg = Release|Any CPU +{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}.Release|Any CPU.Build.0 = Release|Any CPU +{34A31E0B-15EC-829C-6F0B-74F5ACFD97E2}.Release|Any CPU.Deploy.0 = Release|Any CPU +{9B381685-8129-ACBA-66F0-7068FE43A6C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{9B381685-8129-ACBA-66F0-7068FE43A6C3}.Debug|Any CPU.Build.0 = Debug|Any CPU +{9B381685-8129-ACBA-66F0-7068FE43A6C3}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{9B381685-8129-ACBA-66F0-7068FE43A6C3}.Release|Any CPU.ActiveCfg = Release|Any CPU +{9B381685-8129-ACBA-66F0-7068FE43A6C3}.Release|Any CPU.Build.0 = Release|Any CPU +{9B381685-8129-ACBA-66F0-7068FE43A6C3}.Release|Any CPU.Deploy.0 = Release|Any CPU +{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}.Release|Any CPU.Build.0 = Release|Any CPU +{493D1E8E-51C6-DA82-9289-25BD26FAB4A4}.Release|Any CPU.Deploy.0 = Release|Any CPU +{56968E84-6B7D-D548-4C0B-53017BD6123C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{56968E84-6B7D-D548-4C0B-53017BD6123C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{56968E84-6B7D-D548-4C0B-53017BD6123C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{56968E84-6B7D-D548-4C0B-53017BD6123C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{56968E84-6B7D-D548-4C0B-53017BD6123C}.Release|Any CPU.Build.0 = Release|Any CPU +{56968E84-6B7D-D548-4C0B-53017BD6123C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5E741DD9-690A-DE16-E7A1-85E6239AA70D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5E741DD9-690A-DE16-E7A1-85E6239AA70D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5E741DD9-690A-DE16-E7A1-85E6239AA70D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5E741DD9-690A-DE16-E7A1-85E6239AA70D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5E741DD9-690A-DE16-E7A1-85E6239AA70D}.Release|Any CPU.Build.0 = Release|Any CPU +{5E741DD9-690A-DE16-E7A1-85E6239AA70D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{94317D9A-D614-B098-6175-76EE84262C05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{94317D9A-D614-B098-6175-76EE84262C05}.Debug|Any CPU.Build.0 = Debug|Any CPU +{94317D9A-D614-B098-6175-76EE84262C05}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{94317D9A-D614-B098-6175-76EE84262C05}.Release|Any CPU.ActiveCfg = Release|Any CPU +{94317D9A-D614-B098-6175-76EE84262C05}.Release|Any CPU.Build.0 = Release|Any CPU +{94317D9A-D614-B098-6175-76EE84262C05}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F907841F-B1EE-9B12-580E-CFE2324BED03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F907841F-B1EE-9B12-580E-CFE2324BED03}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F907841F-B1EE-9B12-580E-CFE2324BED03}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F907841F-B1EE-9B12-580E-CFE2324BED03}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F907841F-B1EE-9B12-580E-CFE2324BED03}.Release|Any CPU.Build.0 = Release|Any CPU +{F907841F-B1EE-9B12-580E-CFE2324BED03}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}.Release|Any CPU.Build.0 = Release|Any CPU +{C9E4CFA9-C5D3-5E9D-243C-106BA4B6A447}.Release|Any CPU.Deploy.0 = Release|Any CPU +{B0BE4813-D93E-7B06-D422-23CA28ADF22A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B0BE4813-D93E-7B06-D422-23CA28ADF22A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B0BE4813-D93E-7B06-D422-23CA28ADF22A}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{B0BE4813-D93E-7B06-D422-23CA28ADF22A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B0BE4813-D93E-7B06-D422-23CA28ADF22A}.Release|Any CPU.Build.0 = Release|Any CPU +{B0BE4813-D93E-7B06-D422-23CA28ADF22A}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}.Release|Any CPU.Build.0 = Release|Any CPU +{C028861D-F9E8-8231-2B6A-BC3B3FBA349C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}.Debug|Any CPU.Build.0 = Debug|Any CPU +{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}.Release|Any CPU.ActiveCfg = Release|Any CPU +{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}.Release|Any CPU.Build.0 = Release|Any CPU +{64C918A4-27A8-3E9C-E81F-6917F0EDDE90}.Release|Any CPU.Deploy.0 = Release|Any CPU +{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}.Debug|Any CPU.Build.0 = Debug|Any CPU +{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}.Release|Any CPU.ActiveCfg = Release|Any CPU +{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}.Release|Any CPU.Build.0 = Release|Any CPU +{6821B87E-65EB-BFDB-8FDC-8B183EDF739E}.Release|Any CPU.Deploy.0 = Release|Any CPU +{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}.Release|Any CPU.Build.0 = Release|Any CPU +{30FEE563-A3F0-9C50-BFD1-1AF707AAF3C4}.Release|Any CPU.Deploy.0 = Release|Any CPU +{83D6C79A-C71A-D467-284C-28EDBBD059D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{83D6C79A-C71A-D467-284C-28EDBBD059D2}.Debug|Any CPU.Build.0 = Debug|Any CPU +{83D6C79A-C71A-D467-284C-28EDBBD059D2}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{83D6C79A-C71A-D467-284C-28EDBBD059D2}.Release|Any CPU.ActiveCfg = Release|Any CPU +{83D6C79A-C71A-D467-284C-28EDBBD059D2}.Release|Any CPU.Build.0 = Release|Any CPU +{83D6C79A-C71A-D467-284C-28EDBBD059D2}.Release|Any CPU.Deploy.0 = Release|Any CPU +{4AC05C74-08C5-2153-F38C-976975747B5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{4AC05C74-08C5-2153-F38C-976975747B5C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{4AC05C74-08C5-2153-F38C-976975747B5C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{4AC05C74-08C5-2153-F38C-976975747B5C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{4AC05C74-08C5-2153-F38C-976975747B5C}.Release|Any CPU.Build.0 = Release|Any CPU +{4AC05C74-08C5-2153-F38C-976975747B5C}.Release|Any CPU.Deploy.0 = Release|Any CPU +{E2110137-6A36-F4D1-2219-26EB18FEE74D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{E2110137-6A36-F4D1-2219-26EB18FEE74D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{E2110137-6A36-F4D1-2219-26EB18FEE74D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{E2110137-6A36-F4D1-2219-26EB18FEE74D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{E2110137-6A36-F4D1-2219-26EB18FEE74D}.Release|Any CPU.Build.0 = Release|Any CPU +{E2110137-6A36-F4D1-2219-26EB18FEE74D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}.Debug|Any CPU.Build.0 = Debug|Any CPU +{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}.Release|Any CPU.ActiveCfg = Release|Any CPU +{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}.Release|Any CPU.Build.0 = Release|Any CPU +{934EF064-2DCE-6D50-64E9-D4D2C4D41A81}.Release|Any CPU.Deploy.0 = Release|Any CPU +{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}.Debug|Any CPU.Build.0 = Debug|Any CPU +{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}.Release|Any CPU.ActiveCfg = Release|Any CPU +{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}.Release|Any CPU.Build.0 = Release|Any CPU +{3788F245-EA6D-EB5D-80DE-F25AB30A51CC}.Release|Any CPU.Deploy.0 = Release|Any CPU +{EAE89113-1312-F83C-1A4B-638B98E760B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{EAE89113-1312-F83C-1A4B-638B98E760B3}.Debug|Any CPU.Build.0 = Debug|Any CPU +{EAE89113-1312-F83C-1A4B-638B98E760B3}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{EAE89113-1312-F83C-1A4B-638B98E760B3}.Release|Any CPU.ActiveCfg = Release|Any CPU +{EAE89113-1312-F83C-1A4B-638B98E760B3}.Release|Any CPU.Build.0 = Release|Any CPU +{EAE89113-1312-F83C-1A4B-638B98E760B3}.Release|Any CPU.Deploy.0 = Release|Any CPU +{609C8143-BDB3-709B-A7A5-CC33659C9B51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{609C8143-BDB3-709B-A7A5-CC33659C9B51}.Debug|Any CPU.Build.0 = Debug|Any CPU +{609C8143-BDB3-709B-A7A5-CC33659C9B51}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{609C8143-BDB3-709B-A7A5-CC33659C9B51}.Release|Any CPU.ActiveCfg = Release|Any CPU +{609C8143-BDB3-709B-A7A5-CC33659C9B51}.Release|Any CPU.Build.0 = Release|Any CPU +{609C8143-BDB3-709B-A7A5-CC33659C9B51}.Release|Any CPU.Deploy.0 = Release|Any CPU +{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}.Debug|Any CPU.Build.0 = Debug|Any CPU +{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}.Release|Any CPU.ActiveCfg = Release|Any CPU +{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}.Release|Any CPU.Build.0 = Release|Any CPU +{39D13FA7-A1DF-CEA6-ADEE-BAB64A00A843}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}.Release|Any CPU.Build.0 = Release|Any CPU +{5BCE25AB-A4D6-D89C-5274-7EADD8C5967A}.Release|Any CPU.Deploy.0 = Release|Any CPU +{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}.Debug|Any CPU.Build.0 = Debug|Any CPU +{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}.Release|Any CPU.ActiveCfg = Release|Any CPU +{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}.Release|Any CPU.Build.0 = Release|Any CPU +{0D5DC515-9D35-AC02-C0B1-12C70C3163A2}.Release|Any CPU.Deploy.0 = Release|Any CPU +{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}.Debug|Any CPU.Build.0 = Debug|Any CPU +{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}.Release|Any CPU.ActiveCfg = Release|Any CPU +{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}.Release|Any CPU.Build.0 = Release|Any CPU +{F1A91B9A-EC32-5F98-D4D6-75AC04C63276}.Release|Any CPU.Deploy.0 = Release|Any CPU +{74B88D5C-96E5-7286-D2B2-8DEF18538246}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{74B88D5C-96E5-7286-D2B2-8DEF18538246}.Debug|Any CPU.Build.0 = Debug|Any CPU +{74B88D5C-96E5-7286-D2B2-8DEF18538246}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{74B88D5C-96E5-7286-D2B2-8DEF18538246}.Release|Any CPU.ActiveCfg = Release|Any CPU +{74B88D5C-96E5-7286-D2B2-8DEF18538246}.Release|Any CPU.Build.0 = Release|Any CPU +{74B88D5C-96E5-7286-D2B2-8DEF18538246}.Release|Any CPU.Deploy.0 = Release|Any CPU +{D63AC796-7087-BF6C-2848-E6511358FBE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{D63AC796-7087-BF6C-2848-E6511358FBE4}.Debug|Any CPU.Build.0 = Debug|Any CPU +{D63AC796-7087-BF6C-2848-E6511358FBE4}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{D63AC796-7087-BF6C-2848-E6511358FBE4}.Release|Any CPU.ActiveCfg = Release|Any CPU +{D63AC796-7087-BF6C-2848-E6511358FBE4}.Release|Any CPU.Build.0 = Release|Any CPU +{D63AC796-7087-BF6C-2848-E6511358FBE4}.Release|Any CPU.Deploy.0 = Release|Any CPU +{E9FE72C3-56B4-856B-A592-AE6E98E571F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{E9FE72C3-56B4-856B-A592-AE6E98E571F3}.Debug|Any CPU.Build.0 = Debug|Any CPU +{E9FE72C3-56B4-856B-A592-AE6E98E571F3}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{E9FE72C3-56B4-856B-A592-AE6E98E571F3}.Release|Any CPU.ActiveCfg = Release|Any CPU +{E9FE72C3-56B4-856B-A592-AE6E98E571F3}.Release|Any CPU.Build.0 = Release|Any CPU +{E9FE72C3-56B4-856B-A592-AE6E98E571F3}.Release|Any CPU.Deploy.0 = Release|Any CPU +{5DA7DBE9-F180-570F-2DA0-2737F043744D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5DA7DBE9-F180-570F-2DA0-2737F043744D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5DA7DBE9-F180-570F-2DA0-2737F043744D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{5DA7DBE9-F180-570F-2DA0-2737F043744D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5DA7DBE9-F180-570F-2DA0-2737F043744D}.Release|Any CPU.Build.0 = Release|Any CPU +{5DA7DBE9-F180-570F-2DA0-2737F043744D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Release|Any CPU.Build.0 = Release|Any CPU +{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Release|Any CPU.Deploy.0 = Release|Any CPU +{DFBB7B9F-C604-FEDD-E658-17E196043123}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{DFBB7B9F-C604-FEDD-E658-17E196043123}.Debug|Any CPU.Build.0 = Debug|Any CPU +{DFBB7B9F-C604-FEDD-E658-17E196043123}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{DFBB7B9F-C604-FEDD-E658-17E196043123}.Release|Any CPU.ActiveCfg = Release|Any CPU +{DFBB7B9F-C604-FEDD-E658-17E196043123}.Release|Any CPU.Build.0 = Release|Any CPU +{DFBB7B9F-C604-FEDD-E658-17E196043123}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8854C5E8-E40B-74C3-AAFC-DE0F13239276}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8854C5E8-E40B-74C3-AAFC-DE0F13239276}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8854C5E8-E40B-74C3-AAFC-DE0F13239276}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8854C5E8-E40B-74C3-AAFC-DE0F13239276}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8854C5E8-E40B-74C3-AAFC-DE0F13239276}.Release|Any CPU.Build.0 = Release|Any CPU +{8854C5E8-E40B-74C3-AAFC-DE0F13239276}.Release|Any CPU.Deploy.0 = Release|Any CPU +{83D1D75E-3C26-B8D0-F097-F99452E749CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{83D1D75E-3C26-B8D0-F097-F99452E749CC}.Debug|Any CPU.Build.0 = Debug|Any CPU +{83D1D75E-3C26-B8D0-F097-F99452E749CC}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{83D1D75E-3C26-B8D0-F097-F99452E749CC}.Release|Any CPU.ActiveCfg = Release|Any CPU +{83D1D75E-3C26-B8D0-F097-F99452E749CC}.Release|Any CPU.Build.0 = Release|Any CPU +{83D1D75E-3C26-B8D0-F097-F99452E749CC}.Release|Any CPU.Deploy.0 = Release|Any CPU +{7E7D8010-B37A-151A-11A5-1DB234EE1104}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{7E7D8010-B37A-151A-11A5-1DB234EE1104}.Debug|Any CPU.Build.0 = Debug|Any CPU +{7E7D8010-B37A-151A-11A5-1DB234EE1104}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{7E7D8010-B37A-151A-11A5-1DB234EE1104}.Release|Any CPU.ActiveCfg = Release|Any CPU +{7E7D8010-B37A-151A-11A5-1DB234EE1104}.Release|Any CPU.Build.0 = Release|Any CPU +{7E7D8010-B37A-151A-11A5-1DB234EE1104}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}.Release|Any CPU.Build.0 = Release|Any CPU +{C69BDD4D-3EBD-4B8E-CFFB-650903DA3872}.Release|Any CPU.Deploy.0 = Release|Any CPU +{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}.Release|Any CPU.Build.0 = Release|Any CPU +{3B6BBC8A-1B22-DEFF-2980-53B77B6F3E5F}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C27E1919-64F1-CE81-C6D9-B46CED745A12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C27E1919-64F1-CE81-C6D9-B46CED745A12}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C27E1919-64F1-CE81-C6D9-B46CED745A12}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C27E1919-64F1-CE81-C6D9-B46CED745A12}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C27E1919-64F1-CE81-C6D9-B46CED745A12}.Release|Any CPU.Build.0 = Release|Any CPU +{C27E1919-64F1-CE81-C6D9-B46CED745A12}.Release|Any CPU.Deploy.0 = Release|Any CPU +{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}.Debug|Any CPU.Build.0 = Debug|Any CPU +{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}.Release|Any CPU.ActiveCfg = Release|Any CPU +{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}.Release|Any CPU.Build.0 = Release|Any CPU +{05AC8AED-49A4-5C9F-D8C2-8D2DEBF64791}.Release|Any CPU.Deploy.0 = Release|Any CPU +{C00185AF-8735-7674-5FA6-232424B04161}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{C00185AF-8735-7674-5FA6-232424B04161}.Debug|Any CPU.Build.0 = Debug|Any CPU +{C00185AF-8735-7674-5FA6-232424B04161}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{C00185AF-8735-7674-5FA6-232424B04161}.Release|Any CPU.ActiveCfg = Release|Any CPU +{C00185AF-8735-7674-5FA6-232424B04161}.Release|Any CPU.Build.0 = Release|Any CPU +{C00185AF-8735-7674-5FA6-232424B04161}.Release|Any CPU.Deploy.0 = Release|Any CPU +{66B90FB1-20D7-F563-3477-4C7C6B404F4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{66B90FB1-20D7-F563-3477-4C7C6B404F4D}.Debug|Any CPU.Build.0 = Debug|Any CPU +{66B90FB1-20D7-F563-3477-4C7C6B404F4D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{66B90FB1-20D7-F563-3477-4C7C6B404F4D}.Release|Any CPU.ActiveCfg = Release|Any CPU +{66B90FB1-20D7-F563-3477-4C7C6B404F4D}.Release|Any CPU.Build.0 = Release|Any CPU +{66B90FB1-20D7-F563-3477-4C7C6B404F4D}.Release|Any CPU.Deploy.0 = Release|Any CPU +{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}.Debug|Any CPU.Build.0 = Debug|Any CPU +{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}.Release|Any CPU.ActiveCfg = Release|Any CPU +{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}.Release|Any CPU.Build.0 = Release|Any CPU +{4AA72022-0946-6A28-A4E9-6C9ADD5CAEF6}.Release|Any CPU.Deploy.0 = Release|Any CPU +{B22E47E1-9506-56E6-3D19-780B887D8CB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B22E47E1-9506-56E6-3D19-780B887D8CB3}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B22E47E1-9506-56E6-3D19-780B887D8CB3}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{B22E47E1-9506-56E6-3D19-780B887D8CB3}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B22E47E1-9506-56E6-3D19-780B887D8CB3}.Release|Any CPU.Build.0 = Release|Any CPU +{B22E47E1-9506-56E6-3D19-780B887D8CB3}.Release|Any CPU.Deploy.0 = Release|Any CPU +{753BCC52-C451-8B29-6AE7-520B02EE6960}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{753BCC52-C451-8B29-6AE7-520B02EE6960}.Debug|Any CPU.Build.0 = Debug|Any CPU +{753BCC52-C451-8B29-6AE7-520B02EE6960}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{753BCC52-C451-8B29-6AE7-520B02EE6960}.Release|Any CPU.ActiveCfg = Release|Any CPU +{753BCC52-C451-8B29-6AE7-520B02EE6960}.Release|Any CPU.Build.0 = Release|Any CPU +{753BCC52-C451-8B29-6AE7-520B02EE6960}.Release|Any CPU.Deploy.0 = Release|Any CPU +{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}.Debug|Any CPU.Build.0 = Debug|Any CPU +{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}.Release|Any CPU.ActiveCfg = Release|Any CPU +{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}.Release|Any CPU.Build.0 = Release|Any CPU +{B66E3A3E-7945-3D40-24EF-73FA6E1B8D41}.Release|Any CPU.Deploy.0 = Release|Any CPU +{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}.Release|Any CPU.Build.0 = Release|Any CPU +{CD2B60C1-A4B5-36F2-AFA3-6CF1031F9E7F}.Release|Any CPU.Deploy.0 = Release|Any CPU +{8433AAC6-218D-9B7B-6EAA-36774E165446}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{8433AAC6-218D-9B7B-6EAA-36774E165446}.Debug|Any CPU.Build.0 = Debug|Any CPU +{8433AAC6-218D-9B7B-6EAA-36774E165446}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{8433AAC6-218D-9B7B-6EAA-36774E165446}.Release|Any CPU.ActiveCfg = Release|Any CPU +{8433AAC6-218D-9B7B-6EAA-36774E165446}.Release|Any CPU.Build.0 = Release|Any CPU +{8433AAC6-218D-9B7B-6EAA-36774E165446}.Release|Any CPU.Deploy.0 = Release|Any CPU + + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {39648D62-4F58-4C39-9A1C-5A1D884DEDAB} + EndGlobalSection +EndGlobal + diff --git a/UnitsNet.Modular/GeneratedCode/Acceleration/Acceleration.csproj b/UnitsNet.Modular/GeneratedCode/Acceleration/Acceleration.csproj new file mode 100644 index 0000000000..16fe4363f5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Acceleration/Acceleration.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Acceleration</Title> + <Description>Adds Acceleration units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>acceleration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8e3a6691-a05f-d71c-f12a-f537c0807f85}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Acceleration</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Acceleration/Acceleration.g.cs b/UnitsNet.Modular/GeneratedCode/Acceleration/Acceleration.g.cs new file mode 100644 index 0000000000..cd3f27ea37 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Acceleration/Acceleration.g.cs @@ -0,0 +1,1125 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Acceleration : IArithmeticQuantity<Acceleration, AccelerationUnit, double>, IEquatable<Acceleration>, IComparable, IComparable<Acceleration>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AccelerationUnit? _unit; + + static Acceleration() + { + BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); + BaseUnit = AccelerationUnit.MeterPerSecondSquared; + Units = Enum.GetValues(typeof(AccelerationUnit)).Cast<AccelerationUnit>().ToArray(); + Zero = new Acceleration(0, BaseUnit); + Info = new QuantityInfo<AccelerationUnit>("Acceleration", + new UnitInfo<AccelerationUnit>[] + { + new UnitInfo<AccelerationUnit>(AccelerationUnit.CentimeterPerSecondSquared, "CentimetersPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.DecimeterPerSecondSquared, "DecimetersPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.FootPerSecondSquared, "FeetPerSecondSquared", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)), + new UnitInfo<AccelerationUnit>(AccelerationUnit.InchPerSecondSquared, "InchesPerSecondSquared", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second)), + new UnitInfo<AccelerationUnit>(AccelerationUnit.KilometerPerSecondSquared, "KilometersPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.KnotPerHour, "KnotsPerHour", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour)), + new UnitInfo<AccelerationUnit>(AccelerationUnit.KnotPerMinute, "KnotsPerMinute", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Minute)), + new UnitInfo<AccelerationUnit>(AccelerationUnit.KnotPerSecond, "KnotsPerSecond", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Second)), + new UnitInfo<AccelerationUnit>(AccelerationUnit.MeterPerSecondSquared, "MetersPerSecondSquared", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), + new UnitInfo<AccelerationUnit>(AccelerationUnit.MicrometerPerSecondSquared, "MicrometersPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.MillimeterPerSecondSquared, "MillimetersPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.MillistandardGravity, "MillistandardGravity", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.NanometerPerSecondSquared, "NanometersPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<AccelerationUnit>(AccelerationUnit.StandardGravity, "StandardGravity", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Acceleration(double value, AccelerationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Acceleration" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AccelerationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. + /// </summary> + public static AccelerationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Acceleration quantity. + /// </summary> + public static AccelerationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. + /// </summary> + public static Acceleration Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Acceleration AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AccelerationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Acceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.CentimeterPerSecondSquared"/> + /// </summary> + public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.DecimeterPerSecondSquared"/> + /// </summary> + public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.FootPerSecondSquared"/> + /// </summary> + public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.InchPerSecondSquared"/> + /// </summary> + public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.KilometerPerSecondSquared"/> + /// </summary> + public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.KnotPerHour"/> + /// </summary> + public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.KnotPerMinute"/> + /// </summary> + public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.KnotPerSecond"/> + /// </summary> + public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.MeterPerSecondSquared"/> + /// </summary> + public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.MicrometerPerSecondSquared"/> + /// </summary> + public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.MillimeterPerSecondSquared"/> + /// </summary> + public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.MillistandardGravity"/> + /// </summary> + public double MillistandardGravity => As(AccelerationUnit.MillistandardGravity); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.NanometerPerSecondSquared"/> + /// </summary> + public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AccelerationUnit.StandardGravity"/> + /// </summary> + public double StandardGravity => As(AccelerationUnit.StandardGravity); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AccelerationUnit -> BaseUnit + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.CentimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.DecimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.FootPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.InchPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.KilometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.KnotPerHour, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.KnotPerMinute, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.KnotPerSecond, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MicrometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MillimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MillistandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.NanometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.StandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity); + + // Register in unit converter: BaseUnit -> AccelerationUnit + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.CentimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.CentimeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.DecimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.DecimeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.FootPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.FootPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.InchPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.InchPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KilometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.KilometerPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerHour, quantity => quantity.ToUnit(AccelerationUnit.KnotPerHour)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerMinute, quantity => quantity.ToUnit(AccelerationUnit.KnotPerMinute)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerSecond, quantity => quantity.ToUnit(AccelerationUnit.KnotPerSecond)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MicrometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MicrometerPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MillimeterPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillistandardGravity, quantity => quantity.ToUnit(AccelerationUnit.MillistandardGravity)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.NanometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.NanometerPerSecondSquared)); + unitConverter.SetConversionFunction<Acceleration>(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.StandardGravity, quantity => quantity.ToUnit(AccelerationUnit.StandardGravity)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.CentimeterPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"cm/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.CentimeterPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"см/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.DecimeterPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"dm/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.DecimeterPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"дм/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.FootPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"ft/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.FootPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"фут/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.InchPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"in/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.InchPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"дюйм/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KilometerPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"km/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KilometerPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"км/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KnotPerHour, new CultureInfo("en-US"), false, true, new string[]{"kn/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KnotPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"узел/час"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KnotPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kn/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KnotPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"узел/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KnotPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kn/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.KnotPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"узел/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MeterPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"m/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MeterPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"м/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MicrometerPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"µm/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MicrometerPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"мкм/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MillimeterPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"mm/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MillimeterPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"мм/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MillistandardGravity, new CultureInfo("en-US"), false, true, new string[]{"mg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.MillistandardGravity, new CultureInfo("ru-RU"), false, true, new string[]{"мg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.NanometerPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"nm/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.NanometerPerSecondSquared, new CultureInfo("ru-RU"), false, true, new string[]{"нм/с²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.StandardGravity, new CultureInfo("en-US"), false, true, new string[]{"g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AccelerationUnit.StandardGravity, new CultureInfo("ru-RU"), false, true, new string[]{"g"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AccelerationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AccelerationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.CentimeterPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromCentimetersPerSecondSquared(QuantityValue centimeterspersecondsquared) + { + double value = (double) centimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.DecimeterPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromDecimetersPerSecondSquared(QuantityValue decimeterspersecondsquared) + { + double value = (double) decimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.FootPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) + { + double value = (double) feetpersecondsquared; + return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.InchPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) + { + double value = (double) inchespersecondsquared; + return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.KilometerPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromKilometersPerSecondSquared(QuantityValue kilometerspersecondsquared) + { + double value = (double) kilometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.KnotPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) + { + double value = (double) knotsperhour; + return new Acceleration(value, AccelerationUnit.KnotPerHour); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.KnotPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) + { + double value = (double) knotsperminute; + return new Acceleration(value, AccelerationUnit.KnotPerMinute); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.KnotPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) + { + double value = (double) knotspersecond; + return new Acceleration(value, AccelerationUnit.KnotPerSecond); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.MeterPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromMetersPerSecondSquared(QuantityValue meterspersecondsquared) + { + double value = (double) meterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.MicrometerPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromMicrometersPerSecondSquared(QuantityValue micrometerspersecondsquared) + { + double value = (double) micrometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.MillimeterPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromMillimetersPerSecondSquared(QuantityValue millimeterspersecondsquared) + { + double value = (double) millimeterspersecondsquared; + return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.MillistandardGravity"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromMillistandardGravity(QuantityValue millistandardgravity) + { + double value = (double) millistandardgravity; + return new Acceleration(value, AccelerationUnit.MillistandardGravity); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.NanometerPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromNanometersPerSecondSquared(QuantityValue nanometerspersecondsquared) + { + double value = (double) nanometerspersecondsquared; + return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Acceleration"/> from <see cref="AccelerationUnit.StandardGravity"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Acceleration FromStandardGravity(QuantityValue standardgravity) + { + double value = (double) standardgravity; + return new Acceleration(value, AccelerationUnit.StandardGravity); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AccelerationUnit" /> to <see cref="Acceleration" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Acceleration unit value.</returns> + public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) + { + return new Acceleration((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Acceleration Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Acceleration Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Acceleration, AccelerationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Acceleration result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Acceleration result) + { + return QuantityParser.Default.TryParse<Acceleration, AccelerationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AccelerationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AccelerationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AccelerationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AccelerationUnit)"/> + public static bool TryParseUnit(string str, out AccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AccelerationUnit unit) + { + return UnitParser.Default.TryParse<AccelerationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Acceleration operator -(Acceleration right) + { + return new Acceleration(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Acceleration"/> from adding two <see cref="Acceleration"/>.</summary> + public static Acceleration operator +(Acceleration left, Acceleration right) + { + return new Acceleration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Acceleration"/> from subtracting two <see cref="Acceleration"/>.</summary> + public static Acceleration operator -(Acceleration left, Acceleration right) + { + return new Acceleration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Acceleration"/> from multiplying value and <see cref="Acceleration"/>.</summary> + public static Acceleration operator *(double left, Acceleration right) + { + return new Acceleration(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Acceleration"/> from multiplying value and <see cref="Acceleration"/>.</summary> + public static Acceleration operator *(Acceleration left, double right) + { + return new Acceleration(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Acceleration"/> from dividing <see cref="Acceleration"/> by value.</summary> + public static Acceleration operator /(Acceleration left, double right) + { + return new Acceleration(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Acceleration"/> by <see cref="Acceleration"/>.</summary> + public static double operator /(Acceleration left, Acceleration right) + { + return left.MetersPerSecondSquared / right.MetersPerSecondSquared; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Acceleration left, Acceleration right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Acceleration left, Acceleration right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Acceleration left, Acceleration right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Acceleration left, Acceleration right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Acceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Acceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Acceleration left, Acceleration right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Acceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Acceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Acceleration left, Acceleration right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Acceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Acceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Acceleration otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Acceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Acceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Acceleration other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Acceleration"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Acceleration otherQuantity)) throw new ArgumentException("Expected type Acceleration.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Acceleration"/> with another <see cref="Acceleration"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Acceleration other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Acceleration within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Acceleration.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AccelerationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AccelerationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Acceleration to another Acceleration with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Acceleration with the specified unit.</returns> + public Acceleration ToUnit(AccelerationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Acceleration"/> to another <see cref="Acceleration"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Acceleration with the specified unit.</returns> + public Acceleration ToUnit(AccelerationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Acceleration), Unit, typeof(Acceleration), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Acceleration)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Acceleration"/> to another <see cref="Acceleration"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Acceleration"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AccelerationUnit unit, [NotNullWhen(true)] out Acceleration? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Acceleration? convertedOrNull = (Unit, unit) switch + { + // AccelerationUnit -> BaseUnit + (AccelerationUnit.CentimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-2d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.DecimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-1d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.FootPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.304800, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.InchPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.0254, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.KilometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e3d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.KnotPerHour, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.5144444444444 / 3600, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.KnotPerMinute, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.5144444444444 / 60, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.KnotPerSecond, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.5144444444444, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.MicrometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-6d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.MillimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-3d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.MillistandardGravity, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value * 9.80665) * 1e-3d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.NanometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-9d, AccelerationUnit.MeterPerSecondSquared), + (AccelerationUnit.StandardGravity, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 9.80665, AccelerationUnit.MeterPerSecondSquared), + + // BaseUnit -> AccelerationUnit + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.CentimeterPerSecondSquared) => new Acceleration((_value) / 1e-2d, AccelerationUnit.CentimeterPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.DecimeterPerSecondSquared) => new Acceleration((_value) / 1e-1d, AccelerationUnit.DecimeterPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.FootPerSecondSquared) => new Acceleration(_value / 0.304800, AccelerationUnit.FootPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.InchPerSecondSquared) => new Acceleration(_value / 0.0254, AccelerationUnit.InchPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KilometerPerSecondSquared) => new Acceleration((_value) / 1e3d, AccelerationUnit.KilometerPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerHour) => new Acceleration(_value / 0.5144444444444 * 3600, AccelerationUnit.KnotPerHour), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerMinute) => new Acceleration(_value / 0.5144444444444 * 60, AccelerationUnit.KnotPerMinute), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerSecond) => new Acceleration(_value / 0.5144444444444, AccelerationUnit.KnotPerSecond), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MicrometerPerSecondSquared) => new Acceleration((_value) / 1e-6d, AccelerationUnit.MicrometerPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillimeterPerSecondSquared) => new Acceleration((_value) / 1e-3d, AccelerationUnit.MillimeterPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillistandardGravity) => new Acceleration((_value / 9.80665) / 1e-3d, AccelerationUnit.MillistandardGravity), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.NanometerPerSecondSquared) => new Acceleration((_value) / 1e-9d, AccelerationUnit.NanometerPerSecondSquared), + (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.StandardGravity) => new Acceleration(_value / 9.80665, AccelerationUnit.StandardGravity), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AccelerationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AccelerationUnit> IQuantity<AccelerationUnit>.ToUnit(AccelerationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AccelerationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Acceleration)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Acceleration)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Acceleration)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Acceleration)) + return this; + else if (conversionType == typeof(AccelerationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Acceleration.Info; + else if (conversionType == typeof(BaseDimensions)) + return Acceleration.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Acceleration)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Acceleration/AccelerationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Acceleration/AccelerationUnit.g.cs new file mode 100644 index 0000000000..b4f1c48938 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Acceleration/AccelerationUnit.g.cs @@ -0,0 +1,45 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AccelerationUnit + { + CentimeterPerSecondSquared = 1, + DecimeterPerSecondSquared = 2, + FootPerSecondSquared = 3, + InchPerSecondSquared = 4, + KilometerPerSecondSquared = 5, + KnotPerHour = 6, + KnotPerMinute = 7, + KnotPerSecond = 8, + MeterPerSecondSquared = 9, + MicrometerPerSecondSquared = 10, + MillimeterPerSecondSquared = 11, + MillistandardGravity = 12, + NanometerPerSecondSquared = 13, + StandardGravity = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstance.csproj b/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstance.csproj new file mode 100644 index 0000000000..aaecd416dd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET AmountOfSubstance</Title> + <Description>Adds AmountOfSubstance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>amountofsubstance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{1cd282f3-3bdc-bc00-a63a-03a11a9b5c4d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.AmountOfSubstance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstance.g.cs b/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstance.g.cs new file mode 100644 index 0000000000..8194353780 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstance.g.cs @@ -0,0 +1,1132 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct AmountOfSubstance : IArithmeticQuantity<AmountOfSubstance, AmountOfSubstanceUnit, double>, IEquatable<AmountOfSubstance>, IComparable, IComparable<AmountOfSubstance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AmountOfSubstanceUnit? _unit; + + static AmountOfSubstance() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); + BaseUnit = AmountOfSubstanceUnit.Mole; + Units = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast<AmountOfSubstanceUnit>().ToArray(); + Zero = new AmountOfSubstance(0, BaseUnit); + Info = new QuantityInfo<AmountOfSubstanceUnit>("AmountOfSubstance", + new UnitInfo<AmountOfSubstanceUnit>[] + { + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Centimole, "Centimoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.CentipoundMole, "CentipoundMoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Decimole, "Decimoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.DecipoundMole, "DecipoundMoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Kilomole, "Kilomoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.KilopoundMole, "KilopoundMoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Megamole, "Megamoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Micromole, "Micromoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.MicropoundMole, "MicropoundMoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Millimole, "Millimoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.MillipoundMole, "MillipoundMoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Mole, "Moles", new BaseUnits(amount: AmountOfSubstanceUnit.Mole)), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.Nanomole, "Nanomoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.NanopoundMole, "NanopoundMoles", BaseUnits.Undefined), + new UnitInfo<AmountOfSubstanceUnit>(AmountOfSubstanceUnit.PoundMole, "PoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.PoundMole)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public AmountOfSubstance(double value, AmountOfSubstanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="AmountOfSubstance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AmountOfSubstanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. + /// </summary> + public static AmountOfSubstanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the AmountOfSubstance quantity. + /// </summary> + public static AmountOfSubstanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Mole. + /// </summary> + public static AmountOfSubstance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static AmountOfSubstance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AmountOfSubstanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Centimole"/> + /// </summary> + public double Centimoles => As(AmountOfSubstanceUnit.Centimole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.CentipoundMole"/> + /// </summary> + public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Decimole"/> + /// </summary> + public double Decimoles => As(AmountOfSubstanceUnit.Decimole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.DecipoundMole"/> + /// </summary> + public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Kilomole"/> + /// </summary> + public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.KilopoundMole"/> + /// </summary> + public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Megamole"/> + /// </summary> + public double Megamoles => As(AmountOfSubstanceUnit.Megamole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Micromole"/> + /// </summary> + public double Micromoles => As(AmountOfSubstanceUnit.Micromole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.MicropoundMole"/> + /// </summary> + public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Millimole"/> + /// </summary> + public double Millimoles => As(AmountOfSubstanceUnit.Millimole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.MillipoundMole"/> + /// </summary> + public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Mole"/> + /// </summary> + public double Moles => As(AmountOfSubstanceUnit.Mole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.Nanomole"/> + /// </summary> + public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.NanopoundMole"/> + /// </summary> + public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmountOfSubstanceUnit.PoundMole"/> + /// </summary> + public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AmountOfSubstanceUnit -> BaseUnit + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Centimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.CentipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Decimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.DecipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Kilomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.KilopoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Megamole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Micromole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.MicropoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Millimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.MillipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Nanomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.NanopoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.PoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Mole, quantity => quantity); + + // Register in unit converter: BaseUnit -> AmountOfSubstanceUnit + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Centimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Centimole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.CentipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.CentipoundMole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Decimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Decimole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.DecipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.DecipoundMole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Kilomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Kilomole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.KilopoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.KilopoundMole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Megamole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Megamole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Micromole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Micromole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MicropoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.MicropoundMole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Millimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Millimole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MillipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.MillipoundMole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Nanomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Nanomole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.NanopoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.NanopoundMole)); + unitConverter.SetConversionFunction<AmountOfSubstance>(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.PoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.PoundMole)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Centimole, new CultureInfo("en-US"), false, true, new string[]{"cmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.CentipoundMole, new CultureInfo("en-US"), false, true, new string[]{"clbmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Decimole, new CultureInfo("en-US"), false, true, new string[]{"dmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.DecipoundMole, new CultureInfo("en-US"), false, true, new string[]{"dlbmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Kilomole, new CultureInfo("en-US"), false, true, new string[]{"kmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.KilopoundMole, new CultureInfo("en-US"), false, true, new string[]{"klbmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Megamole, new CultureInfo("en-US"), false, true, new string[]{"Mmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Micromole, new CultureInfo("en-US"), false, true, new string[]{"µmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.MicropoundMole, new CultureInfo("en-US"), false, true, new string[]{"µlbmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Millimole, new CultureInfo("en-US"), false, true, new string[]{"mmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.MillipoundMole, new CultureInfo("en-US"), false, true, new string[]{"mlbmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Mole, new CultureInfo("en-US"), false, true, new string[]{"mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.Nanomole, new CultureInfo("en-US"), false, true, new string[]{"nmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.NanopoundMole, new CultureInfo("en-US"), false, true, new string[]{"nlbmol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmountOfSubstanceUnit.PoundMole, new CultureInfo("en-US"), false, true, new string[]{"lbmol"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AmountOfSubstanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AmountOfSubstanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Centimole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) + { + double value = (double) centimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.CentipoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) + { + double value = (double) centipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Decimole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) + { + double value = (double) decimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.DecipoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) + { + double value = (double) decipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Kilomole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) + { + double value = (double) kilomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.KilopoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) + { + double value = (double) kilopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Megamole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromMegamoles(QuantityValue megamoles) + { + double value = (double) megamoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Megamole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Micromole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) + { + double value = (double) micromoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.MicropoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) + { + double value = (double) micropoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Millimole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) + { + double value = (double) millimoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.MillipoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) + { + double value = (double) millipoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Mole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromMoles(QuantityValue moles) + { + double value = (double) moles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.Nanomole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) + { + double value = (double) nanomoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.NanopoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) + { + double value = (double) nanopoundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); + } + + /// <summary> + /// Creates a <see cref="AmountOfSubstance"/> from <see cref="AmountOfSubstanceUnit.PoundMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) + { + double value = (double) poundmoles; + return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AmountOfSubstanceUnit" /> to <see cref="AmountOfSubstance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>AmountOfSubstance unit value.</returns> + public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) + { + return new AmountOfSubstance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static AmountOfSubstance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static AmountOfSubstance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<AmountOfSubstance, AmountOfSubstanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out AmountOfSubstance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out AmountOfSubstance result) + { + return QuantityParser.Default.TryParse<AmountOfSubstance, AmountOfSubstanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AmountOfSubstanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AmountOfSubstanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AmountOfSubstanceUnit)"/> + public static bool TryParseUnit(string str, out AmountOfSubstanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AmountOfSubstanceUnit unit) + { + return UnitParser.Default.TryParse<AmountOfSubstanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static AmountOfSubstance operator -(AmountOfSubstance right) + { + return new AmountOfSubstance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="AmountOfSubstance"/> from adding two <see cref="AmountOfSubstance"/>.</summary> + public static AmountOfSubstance operator +(AmountOfSubstance left, AmountOfSubstance right) + { + return new AmountOfSubstance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="AmountOfSubstance"/> from subtracting two <see cref="AmountOfSubstance"/>.</summary> + public static AmountOfSubstance operator -(AmountOfSubstance left, AmountOfSubstance right) + { + return new AmountOfSubstance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="AmountOfSubstance"/> from multiplying value and <see cref="AmountOfSubstance"/>.</summary> + public static AmountOfSubstance operator *(double left, AmountOfSubstance right) + { + return new AmountOfSubstance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="AmountOfSubstance"/> from multiplying value and <see cref="AmountOfSubstance"/>.</summary> + public static AmountOfSubstance operator *(AmountOfSubstance left, double right) + { + return new AmountOfSubstance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="AmountOfSubstance"/> from dividing <see cref="AmountOfSubstance"/> by value.</summary> + public static AmountOfSubstance operator /(AmountOfSubstance left, double right) + { + return new AmountOfSubstance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="AmountOfSubstance"/> by <see cref="AmountOfSubstance"/>.</summary> + public static double operator /(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Moles / right.Moles; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="AmountOfSubstance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmountOfSubstance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="AmountOfSubstance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmountOfSubstance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AmountOfSubstance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmountOfSubstance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is AmountOfSubstance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AmountOfSubstance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmountOfSubstance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(AmountOfSubstance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="AmountOfSubstance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is AmountOfSubstance otherQuantity)) throw new ArgumentException("Expected type AmountOfSubstance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="AmountOfSubstance"/> with another <see cref="AmountOfSubstance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(AmountOfSubstance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another AmountOfSubstance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current AmountOfSubstance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AmountOfSubstanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AmountOfSubstanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A AmountOfSubstance with the specified unit.</returns> + public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="AmountOfSubstance"/> to another <see cref="AmountOfSubstance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A AmountOfSubstance with the specified unit.</returns> + public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(AmountOfSubstance), Unit, typeof(AmountOfSubstance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (AmountOfSubstance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="AmountOfSubstance"/> to another <see cref="AmountOfSubstance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="AmountOfSubstance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AmountOfSubstanceUnit unit, [NotNullWhen(true)] out AmountOfSubstance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + AmountOfSubstance? convertedOrNull = (Unit, unit) switch + { + // AmountOfSubstanceUnit -> BaseUnit + (AmountOfSubstanceUnit.Centimole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-2d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.CentipoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-2d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.Decimole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-1d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.DecipoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-1d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.Kilomole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e3d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.KilopoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e3d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.Megamole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e6d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.Micromole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-6d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.MicropoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-6d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.Millimole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-3d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.MillipoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-3d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.Nanomole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-9d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.NanopoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-9d, AmountOfSubstanceUnit.Mole), + (AmountOfSubstanceUnit.PoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance(_value * 453.59237, AmountOfSubstanceUnit.Mole), + + // BaseUnit -> AmountOfSubstanceUnit + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Centimole) => new AmountOfSubstance((_value) / 1e-2d, AmountOfSubstanceUnit.Centimole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.CentipoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-2d, AmountOfSubstanceUnit.CentipoundMole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Decimole) => new AmountOfSubstance((_value) / 1e-1d, AmountOfSubstanceUnit.Decimole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.DecipoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-1d, AmountOfSubstanceUnit.DecipoundMole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Kilomole) => new AmountOfSubstance((_value) / 1e3d, AmountOfSubstanceUnit.Kilomole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.KilopoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e3d, AmountOfSubstanceUnit.KilopoundMole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Megamole) => new AmountOfSubstance((_value) / 1e6d, AmountOfSubstanceUnit.Megamole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Micromole) => new AmountOfSubstance((_value) / 1e-6d, AmountOfSubstanceUnit.Micromole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MicropoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-6d, AmountOfSubstanceUnit.MicropoundMole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Millimole) => new AmountOfSubstance((_value) / 1e-3d, AmountOfSubstanceUnit.Millimole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MillipoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-3d, AmountOfSubstanceUnit.MillipoundMole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Nanomole) => new AmountOfSubstance((_value) / 1e-9d, AmountOfSubstanceUnit.Nanomole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.NanopoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-9d, AmountOfSubstanceUnit.NanopoundMole), + (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.PoundMole) => new AmountOfSubstance(_value / 453.59237, AmountOfSubstanceUnit.PoundMole), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AmountOfSubstanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AmountOfSubstanceUnit> IQuantity<AmountOfSubstanceUnit>.ToUnit(AmountOfSubstanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AmountOfSubstanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(AmountOfSubstance)) + return this; + else if (conversionType == typeof(AmountOfSubstanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return AmountOfSubstance.Info; + else if (conversionType == typeof(BaseDimensions)) + return AmountOfSubstance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstanceUnit.g.cs new file mode 100644 index 0000000000..e0ce7a5da7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AmountOfSubstance/AmountOfSubstanceUnit.g.cs @@ -0,0 +1,46 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AmountOfSubstanceUnit + { + Centimole = 1, + CentipoundMole = 2, + Decimole = 3, + DecipoundMole = 4, + Kilomole = 5, + KilopoundMole = 6, + Megamole = 7, + Micromole = 8, + MicropoundMole = 9, + Millimole = 10, + MillipoundMole = 11, + Mole = 12, + Nanomole = 13, + NanopoundMole = 14, + PoundMole = 15, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatio.csproj b/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatio.csproj new file mode 100644 index 0000000000..d9bd853443 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatio.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET AmplitudeRatio</Title> + <Description>Adds AmplitudeRatio units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>amplituderatio unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{59c09a1b-eff0-e367-6372-d16c4c984916}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.AmplitudeRatio</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatio.g.cs b/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatio.g.cs new file mode 100644 index 0000000000..e1a7d25d8d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatio.g.cs @@ -0,0 +1,909 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. + /// </summary> + [DataContract] + public readonly partial struct AmplitudeRatio : IArithmeticQuantity<AmplitudeRatio, AmplitudeRatioUnit, double>, IEquatable<AmplitudeRatio>, IComparable, IComparable<AmplitudeRatio>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AmplitudeRatioUnit? _unit; + + static AmplitudeRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = AmplitudeRatioUnit.DecibelVolt; + Units = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast<AmplitudeRatioUnit>().ToArray(); + Zero = new AmplitudeRatio(0, BaseUnit); + Info = new QuantityInfo<AmplitudeRatioUnit>("AmplitudeRatio", + new UnitInfo<AmplitudeRatioUnit>[] + { + new UnitInfo<AmplitudeRatioUnit>(AmplitudeRatioUnit.DecibelMicrovolt, "DecibelMicrovolts", BaseUnits.Undefined), + new UnitInfo<AmplitudeRatioUnit>(AmplitudeRatioUnit.DecibelMillivolt, "DecibelMillivolts", BaseUnits.Undefined), + new UnitInfo<AmplitudeRatioUnit>(AmplitudeRatioUnit.DecibelUnloaded, "DecibelsUnloaded", BaseUnits.Undefined), + new UnitInfo<AmplitudeRatioUnit>(AmplitudeRatioUnit.DecibelVolt, "DecibelVolts", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public AmplitudeRatio(double value, AmplitudeRatioUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="AmplitudeRatio" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AmplitudeRatioUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. + /// </summary> + public static AmplitudeRatioUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the AmplitudeRatio quantity. + /// </summary> + public static AmplitudeRatioUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. + /// </summary> + public static AmplitudeRatio Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static AmplitudeRatio AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AmplitudeRatioUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmplitudeRatioUnit.DecibelMicrovolt"/> + /// </summary> + public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmplitudeRatioUnit.DecibelMillivolt"/> + /// </summary> + public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmplitudeRatioUnit.DecibelUnloaded"/> + /// </summary> + public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AmplitudeRatioUnit.DecibelVolt"/> + /// </summary> + public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AmplitudeRatioUnit -> BaseUnit + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelVolt)); + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelMillivolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelVolt)); + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelUnloaded, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelVolt)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity); + + // Register in unit converter: BaseUnit -> AmplitudeRatioUnit + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMicrovolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelMicrovolt)); + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMillivolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelMillivolt)); + unitConverter.SetConversionFunction<AmplitudeRatio>(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelUnloaded, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelUnloaded)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AmplitudeRatioUnit.DecibelMicrovolt, new CultureInfo("en-US"), false, true, new string[]{"dBµV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmplitudeRatioUnit.DecibelMillivolt, new CultureInfo("en-US"), false, true, new string[]{"dBmV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmplitudeRatioUnit.DecibelUnloaded, new CultureInfo("en-US"), false, true, new string[]{"dBu"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AmplitudeRatioUnit.DecibelVolt, new CultureInfo("en-US"), false, true, new string[]{"dBV"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AmplitudeRatioUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AmplitudeRatioUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="AmplitudeRatio"/> from <see cref="AmplitudeRatioUnit.DecibelMicrovolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) + { + double value = (double) decibelmicrovolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); + } + + /// <summary> + /// Creates a <see cref="AmplitudeRatio"/> from <see cref="AmplitudeRatioUnit.DecibelMillivolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) + { + double value = (double) decibelmillivolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); + } + + /// <summary> + /// Creates a <see cref="AmplitudeRatio"/> from <see cref="AmplitudeRatioUnit.DecibelUnloaded"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) + { + double value = (double) decibelsunloaded; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); + } + + /// <summary> + /// Creates a <see cref="AmplitudeRatio"/> from <see cref="AmplitudeRatioUnit.DecibelVolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) + { + double value = (double) decibelvolts; + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AmplitudeRatioUnit" /> to <see cref="AmplitudeRatio" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>AmplitudeRatio unit value.</returns> + public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) + { + return new AmplitudeRatio((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static AmplitudeRatio Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static AmplitudeRatio Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<AmplitudeRatio, AmplitudeRatioUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out AmplitudeRatio result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out AmplitudeRatio result) + { + return QuantityParser.Default.TryParse<AmplitudeRatio, AmplitudeRatioUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AmplitudeRatioUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AmplitudeRatioUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AmplitudeRatioUnit)"/> + public static bool TryParseUnit(string str, out AmplitudeRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AmplitudeRatioUnit unit) + { + return UnitParser.Default.TryParse<AmplitudeRatioUnit>(str, provider, out unit); + } + + #endregion + + #region Logarithmic Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static AmplitudeRatio operator -(AmplitudeRatio right) + { + return new AmplitudeRatio(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="AmplitudeRatio"/> from logarithmic addition of two <see cref="AmplitudeRatio"/>.</summary> + 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.ToUnit(left.Unit).Value / 20)), left.Unit); + } + + /// <summary>Get <see cref="AmplitudeRatio"/> from logarithmic subtraction of two <see cref="AmplitudeRatio"/>.</summary> + 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.ToUnit(left.Unit).Value / 20)), left.Unit); + } + + /// <summary>Get <see cref="AmplitudeRatio"/> from logarithmic multiplication of value and <see cref="AmplitudeRatio"/>.</summary> + public static AmplitudeRatio operator *(double left, AmplitudeRatio right) + { + // Logarithmic multiplication = addition + return new AmplitudeRatio(left + right.Value, right.Unit); + } + + /// <summary>Get <see cref="AmplitudeRatio"/> from logarithmic multiplication of value and <see cref="AmplitudeRatio"/>.</summary> + public static AmplitudeRatio operator *(AmplitudeRatio left, double right) + { + // Logarithmic multiplication = addition + return new AmplitudeRatio(left.Value + (double)right, left.Unit); + } + + /// <summary>Get <see cref="AmplitudeRatio"/> from logarithmic division of <see cref="AmplitudeRatio"/> by value.</summary> + public static AmplitudeRatio operator /(AmplitudeRatio left, double right) + { + // Logarithmic division = subtraction + return new AmplitudeRatio(left.Value - (double)right, left.Unit); + } + + /// <summary>Get ratio value from logarithmic division of <see cref="AmplitudeRatio"/> by <see cref="AmplitudeRatio"/>.</summary> + public static double operator /(AmplitudeRatio left, AmplitudeRatio right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="AmplitudeRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmplitudeRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="AmplitudeRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmplitudeRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AmplitudeRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmplitudeRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is AmplitudeRatio otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AmplitudeRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AmplitudeRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(AmplitudeRatio other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="AmplitudeRatio"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is AmplitudeRatio otherQuantity)) throw new ArgumentException("Expected type AmplitudeRatio.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="AmplitudeRatio"/> with another <see cref="AmplitudeRatio"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(AmplitudeRatio other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another AmplitudeRatio within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current AmplitudeRatio.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AmplitudeRatioUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AmplitudeRatioUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A AmplitudeRatio with the specified unit.</returns> + public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="AmplitudeRatio"/> to another <see cref="AmplitudeRatio"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A AmplitudeRatio with the specified unit.</returns> + public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(AmplitudeRatio), Unit, typeof(AmplitudeRatio), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (AmplitudeRatio)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="AmplitudeRatio"/> to another <see cref="AmplitudeRatio"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="AmplitudeRatio"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AmplitudeRatioUnit unit, [NotNullWhen(true)] out AmplitudeRatio? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + AmplitudeRatio? convertedOrNull = (Unit, unit) switch + { + // AmplitudeRatioUnit -> BaseUnit + (AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatioUnit.DecibelVolt) => new AmplitudeRatio(_value - 120, AmplitudeRatioUnit.DecibelVolt), + (AmplitudeRatioUnit.DecibelMillivolt, AmplitudeRatioUnit.DecibelVolt) => new AmplitudeRatio(_value - 60, AmplitudeRatioUnit.DecibelVolt), + (AmplitudeRatioUnit.DecibelUnloaded, AmplitudeRatioUnit.DecibelVolt) => new AmplitudeRatio(_value - 2.218487499, AmplitudeRatioUnit.DecibelVolt), + + // BaseUnit -> AmplitudeRatioUnit + (AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMicrovolt) => new AmplitudeRatio(_value + 120, AmplitudeRatioUnit.DecibelMicrovolt), + (AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMillivolt) => new AmplitudeRatio(_value + 60, AmplitudeRatioUnit.DecibelMillivolt), + (AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelUnloaded) => new AmplitudeRatio(_value + 2.218487499, AmplitudeRatioUnit.DecibelUnloaded), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AmplitudeRatioUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AmplitudeRatioUnit> IQuantity<AmplitudeRatioUnit>.ToUnit(AmplitudeRatioUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AmplitudeRatioUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(AmplitudeRatio)) + return this; + else if (conversionType == typeof(AmplitudeRatioUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return AmplitudeRatio.Info; + else if (conversionType == typeof(BaseDimensions)) + return AmplitudeRatio.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatioUnit.g.cs b/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatioUnit.g.cs new file mode 100644 index 0000000000..97a8d592f6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AmplitudeRatio/AmplitudeRatioUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AmplitudeRatioUnit + { + DecibelMicrovolt = 1, + DecibelMillivolt = 2, + DecibelUnloaded = 3, + DecibelVolt = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Angle/Angle.csproj b/UnitsNet.Modular/GeneratedCode/Angle/Angle.csproj new file mode 100644 index 0000000000..cb228889b2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Angle/Angle.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Angle</Title> + <Description>Adds Angle units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>angle unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{4b036819-f813-0c4d-3e44-1fcc8b5f3ec7}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Angle</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Angle/Angle.g.cs b/UnitsNet.Modular/GeneratedCode/Angle/Angle.g.cs new file mode 100644 index 0000000000..ef9b2c889b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Angle/Angle.g.cs @@ -0,0 +1,1165 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Angle : IArithmeticQuantity<Angle, AngleUnit, double>, IEquatable<Angle>, IComparable, IComparable<Angle>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AngleUnit? _unit; + + static Angle() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = AngleUnit.Degree; + Units = Enum.GetValues(typeof(AngleUnit)).Cast<AngleUnit>().ToArray(); + Zero = new Angle(0, BaseUnit); + Info = new QuantityInfo<AngleUnit>("Angle", + new UnitInfo<AngleUnit>[] + { + new UnitInfo<AngleUnit>(AngleUnit.Arcminute, "Arcminutes", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Arcsecond, "Arcseconds", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Centiradian, "Centiradians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Deciradian, "Deciradians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Degree, "Degrees", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Gradian, "Gradians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Microdegree, "Microdegrees", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Microradian, "Microradians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Millidegree, "Millidegrees", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Milliradian, "Milliradians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Nanodegree, "Nanodegrees", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Nanoradian, "Nanoradians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.NatoMil, "NatoMils", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Radian, "Radians", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Revolution, "Revolutions", BaseUnits.Undefined), + new UnitInfo<AngleUnit>(AngleUnit.Tilt, "Tilt", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Angle(double value, AngleUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Angle" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AngleUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Angle, which is Degree. All conversions go via this value. + /// </summary> + public static AngleUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Angle quantity. + /// </summary> + public static AngleUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Degree. + /// </summary> + public static Angle Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Angle AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AngleUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Angle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Arcminute"/> + /// </summary> + public double Arcminutes => As(AngleUnit.Arcminute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Arcsecond"/> + /// </summary> + public double Arcseconds => As(AngleUnit.Arcsecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Centiradian"/> + /// </summary> + public double Centiradians => As(AngleUnit.Centiradian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Deciradian"/> + /// </summary> + public double Deciradians => As(AngleUnit.Deciradian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Degree"/> + /// </summary> + public double Degrees => As(AngleUnit.Degree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Gradian"/> + /// </summary> + public double Gradians => As(AngleUnit.Gradian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Microdegree"/> + /// </summary> + public double Microdegrees => As(AngleUnit.Microdegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Microradian"/> + /// </summary> + public double Microradians => As(AngleUnit.Microradian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Millidegree"/> + /// </summary> + public double Millidegrees => As(AngleUnit.Millidegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Milliradian"/> + /// </summary> + public double Milliradians => As(AngleUnit.Milliradian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Nanodegree"/> + /// </summary> + public double Nanodegrees => As(AngleUnit.Nanodegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Nanoradian"/> + /// </summary> + public double Nanoradians => As(AngleUnit.Nanoradian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.NatoMil"/> + /// </summary> + public double NatoMils => As(AngleUnit.NatoMil); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Radian"/> + /// </summary> + public double Radians => As(AngleUnit.Radian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Revolution"/> + /// </summary> + public double Revolutions => As(AngleUnit.Revolution); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AngleUnit.Tilt"/> + /// </summary> + public double Tilt => As(AngleUnit.Tilt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AngleUnit -> BaseUnit + unitConverter.SetConversionFunction<Angle>(AngleUnit.Arcminute, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Arcsecond, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Centiradian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Deciradian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Gradian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Microdegree, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Microradian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Millidegree, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Milliradian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Nanodegree, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Nanoradian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.NatoMil, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Radian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Revolution, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Tilt, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Degree, quantity => quantity); + + // Register in unit converter: BaseUnit -> AngleUnit + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Arcminute, quantity => quantity.ToUnit(AngleUnit.Arcminute)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Arcsecond, quantity => quantity.ToUnit(AngleUnit.Arcsecond)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Centiradian, quantity => quantity.ToUnit(AngleUnit.Centiradian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Deciradian, quantity => quantity.ToUnit(AngleUnit.Deciradian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Gradian, quantity => quantity.ToUnit(AngleUnit.Gradian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Microdegree, quantity => quantity.ToUnit(AngleUnit.Microdegree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Microradian, quantity => quantity.ToUnit(AngleUnit.Microradian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Millidegree, quantity => quantity.ToUnit(AngleUnit.Millidegree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Milliradian, quantity => quantity.ToUnit(AngleUnit.Milliradian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Nanodegree, quantity => quantity.ToUnit(AngleUnit.Nanodegree)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Nanoradian, quantity => quantity.ToUnit(AngleUnit.Nanoradian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.NatoMil, quantity => quantity.ToUnit(AngleUnit.NatoMil)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Revolution, quantity => quantity.ToUnit(AngleUnit.Revolution)); + unitConverter.SetConversionFunction<Angle>(AngleUnit.Degree, AngleUnit.Tilt, quantity => quantity.ToUnit(AngleUnit.Tilt)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Arcminute, new CultureInfo("en-US"), false, true, new string[]{"'", "arcmin", "amin", "min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Arcsecond, new CultureInfo("en-US"), false, true, new string[]{"″", "arcsec", "asec", "sec"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Centiradian, new CultureInfo("en-US"), false, true, new string[]{"crad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Centiradian, new CultureInfo("ru-RU"), false, true, new string[]{"срад"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Deciradian, new CultureInfo("en-US"), false, true, new string[]{"drad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Deciradian, new CultureInfo("ru-RU"), false, true, new string[]{"драд"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Degree, new CultureInfo("en-US"), false, true, new string[]{"°", "deg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Degree, new CultureInfo("ru-RU"), false, true, new string[]{"°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Gradian, new CultureInfo("en-US"), false, true, new string[]{"g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Gradian, new CultureInfo("ru-RU"), false, true, new string[]{"g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Microdegree, new CultureInfo("en-US"), false, true, new string[]{"µ°", "µdeg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Microdegree, new CultureInfo("ru-RU"), false, true, new string[]{"мк°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Microradian, new CultureInfo("en-US"), false, true, new string[]{"µrad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Microradian, new CultureInfo("ru-RU"), false, true, new string[]{"мкрад"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Millidegree, new CultureInfo("en-US"), false, true, new string[]{"m°", "mdeg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Millidegree, new CultureInfo("ru-RU"), false, true, new string[]{"м°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Milliradian, new CultureInfo("en-US"), false, true, new string[]{"mrad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Milliradian, new CultureInfo("ru-RU"), false, true, new string[]{"мрад"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Nanodegree, new CultureInfo("en-US"), false, true, new string[]{"n°", "ndeg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Nanodegree, new CultureInfo("ru-RU"), false, true, new string[]{"н°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Nanoradian, new CultureInfo("en-US"), false, true, new string[]{"nrad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Nanoradian, new CultureInfo("ru-RU"), false, true, new string[]{"нрад"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.NatoMil, new CultureInfo("en-US"), false, true, new string[]{"mil"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Radian, new CultureInfo("en-US"), false, true, new string[]{"rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Radian, new CultureInfo("ru-RU"), false, true, new string[]{"рад"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Revolution, new CultureInfo("en-US"), false, true, new string[]{"r"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Revolution, new CultureInfo("ru-RU"), false, true, new string[]{"r"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AngleUnit.Tilt, new CultureInfo("en-US"), false, true, new string[]{"sin(θ)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AngleUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AngleUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Arcminute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromArcminutes(QuantityValue arcminutes) + { + double value = (double) arcminutes; + return new Angle(value, AngleUnit.Arcminute); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Arcsecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromArcseconds(QuantityValue arcseconds) + { + double value = (double) arcseconds; + return new Angle(value, AngleUnit.Arcsecond); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Centiradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromCentiradians(QuantityValue centiradians) + { + double value = (double) centiradians; + return new Angle(value, AngleUnit.Centiradian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Deciradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromDeciradians(QuantityValue deciradians) + { + double value = (double) deciradians; + return new Angle(value, AngleUnit.Deciradian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Degree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromDegrees(QuantityValue degrees) + { + double value = (double) degrees; + return new Angle(value, AngleUnit.Degree); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Gradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromGradians(QuantityValue gradians) + { + double value = (double) gradians; + return new Angle(value, AngleUnit.Gradian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Microdegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromMicrodegrees(QuantityValue microdegrees) + { + double value = (double) microdegrees; + return new Angle(value, AngleUnit.Microdegree); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Microradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromMicroradians(QuantityValue microradians) + { + double value = (double) microradians; + return new Angle(value, AngleUnit.Microradian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Millidegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromMillidegrees(QuantityValue millidegrees) + { + double value = (double) millidegrees; + return new Angle(value, AngleUnit.Millidegree); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Milliradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromMilliradians(QuantityValue milliradians) + { + double value = (double) milliradians; + return new Angle(value, AngleUnit.Milliradian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Nanodegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromNanodegrees(QuantityValue nanodegrees) + { + double value = (double) nanodegrees; + return new Angle(value, AngleUnit.Nanodegree); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Nanoradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromNanoradians(QuantityValue nanoradians) + { + double value = (double) nanoradians; + return new Angle(value, AngleUnit.Nanoradian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.NatoMil"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromNatoMils(QuantityValue natomils) + { + double value = (double) natomils; + return new Angle(value, AngleUnit.NatoMil); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Radian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromRadians(QuantityValue radians) + { + double value = (double) radians; + return new Angle(value, AngleUnit.Radian); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Revolution"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromRevolutions(QuantityValue revolutions) + { + double value = (double) revolutions; + return new Angle(value, AngleUnit.Revolution); + } + + /// <summary> + /// Creates a <see cref="Angle"/> from <see cref="AngleUnit.Tilt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Angle FromTilt(QuantityValue tilt) + { + double value = (double) tilt; + return new Angle(value, AngleUnit.Tilt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AngleUnit" /> to <see cref="Angle" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Angle unit value.</returns> + public static Angle From(QuantityValue value, AngleUnit fromUnit) + { + return new Angle((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Angle Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Angle Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Angle, AngleUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Angle result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Angle result) + { + return QuantityParser.Default.TryParse<Angle, AngleUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AngleUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AngleUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AngleUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AngleUnit)"/> + public static bool TryParseUnit(string str, out AngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AngleUnit unit) + { + return UnitParser.Default.TryParse<AngleUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Angle operator -(Angle right) + { + return new Angle(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Angle"/> from adding two <see cref="Angle"/>.</summary> + public static Angle operator +(Angle left, Angle right) + { + return new Angle(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Angle"/> from subtracting two <see cref="Angle"/>.</summary> + public static Angle operator -(Angle left, Angle right) + { + return new Angle(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Angle"/> from multiplying value and <see cref="Angle"/>.</summary> + public static Angle operator *(double left, Angle right) + { + return new Angle(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Angle"/> from multiplying value and <see cref="Angle"/>.</summary> + public static Angle operator *(Angle left, double right) + { + return new Angle(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Angle"/> from dividing <see cref="Angle"/> by value.</summary> + public static Angle operator /(Angle left, double right) + { + return new Angle(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Angle"/> by <see cref="Angle"/>.</summary> + public static double operator /(Angle left, Angle right) + { + return left.Degrees / right.Degrees; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Angle left, Angle right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Angle left, Angle right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Angle left, Angle right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Angle left, Angle right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Angle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Angle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Angle left, Angle right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Angle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Angle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Angle left, Angle right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Angle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Angle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Angle otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Angle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Angle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Angle other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Angle"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Angle otherQuantity)) throw new ArgumentException("Expected type Angle.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Angle"/> with another <see cref="Angle"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Angle other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Angle within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Angle.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AngleUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AngleUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Angle to another Angle with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Angle with the specified unit.</returns> + public Angle ToUnit(AngleUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Angle"/> to another <see cref="Angle"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Angle with the specified unit.</returns> + public Angle ToUnit(AngleUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Angle), Unit, typeof(Angle), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Angle)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Angle"/> to another <see cref="Angle"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Angle"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AngleUnit unit, [NotNullWhen(true)] out Angle? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Angle? convertedOrNull = (Unit, unit) switch + { + // AngleUnit -> BaseUnit + (AngleUnit.Arcminute, AngleUnit.Degree) => new Angle(_value / 60, AngleUnit.Degree), + (AngleUnit.Arcsecond, AngleUnit.Degree) => new Angle(_value / 3600, AngleUnit.Degree), + (AngleUnit.Centiradian, AngleUnit.Degree) => new Angle((_value * 180 / Math.PI) * 1e-2d, AngleUnit.Degree), + (AngleUnit.Deciradian, AngleUnit.Degree) => new Angle((_value * 180 / Math.PI) * 1e-1d, AngleUnit.Degree), + (AngleUnit.Gradian, AngleUnit.Degree) => new Angle(_value * 0.9, AngleUnit.Degree), + (AngleUnit.Microdegree, AngleUnit.Degree) => new Angle((_value) * 1e-6d, AngleUnit.Degree), + (AngleUnit.Microradian, AngleUnit.Degree) => new Angle((_value * 180 / Math.PI) * 1e-6d, AngleUnit.Degree), + (AngleUnit.Millidegree, AngleUnit.Degree) => new Angle((_value) * 1e-3d, AngleUnit.Degree), + (AngleUnit.Milliradian, AngleUnit.Degree) => new Angle((_value * 180 / Math.PI) * 1e-3d, AngleUnit.Degree), + (AngleUnit.Nanodegree, AngleUnit.Degree) => new Angle((_value) * 1e-9d, AngleUnit.Degree), + (AngleUnit.Nanoradian, AngleUnit.Degree) => new Angle((_value * 180 / Math.PI) * 1e-9d, AngleUnit.Degree), + (AngleUnit.NatoMil, AngleUnit.Degree) => new Angle(_value * 9 / 160, AngleUnit.Degree), + (AngleUnit.Radian, AngleUnit.Degree) => new Angle(_value * 180 / Math.PI, AngleUnit.Degree), + (AngleUnit.Revolution, AngleUnit.Degree) => new Angle(_value * 360, AngleUnit.Degree), + (AngleUnit.Tilt, AngleUnit.Degree) => new Angle(Math.Asin(_value) * 180 / Math.PI, AngleUnit.Degree), + + // BaseUnit -> AngleUnit + (AngleUnit.Degree, AngleUnit.Arcminute) => new Angle(_value * 60, AngleUnit.Arcminute), + (AngleUnit.Degree, AngleUnit.Arcsecond) => new Angle(_value * 3600, AngleUnit.Arcsecond), + (AngleUnit.Degree, AngleUnit.Centiradian) => new Angle((_value / 180 * Math.PI) / 1e-2d, AngleUnit.Centiradian), + (AngleUnit.Degree, AngleUnit.Deciradian) => new Angle((_value / 180 * Math.PI) / 1e-1d, AngleUnit.Deciradian), + (AngleUnit.Degree, AngleUnit.Gradian) => new Angle(_value / 0.9, AngleUnit.Gradian), + (AngleUnit.Degree, AngleUnit.Microdegree) => new Angle((_value) / 1e-6d, AngleUnit.Microdegree), + (AngleUnit.Degree, AngleUnit.Microradian) => new Angle((_value / 180 * Math.PI) / 1e-6d, AngleUnit.Microradian), + (AngleUnit.Degree, AngleUnit.Millidegree) => new Angle((_value) / 1e-3d, AngleUnit.Millidegree), + (AngleUnit.Degree, AngleUnit.Milliradian) => new Angle((_value / 180 * Math.PI) / 1e-3d, AngleUnit.Milliradian), + (AngleUnit.Degree, AngleUnit.Nanodegree) => new Angle((_value) / 1e-9d, AngleUnit.Nanodegree), + (AngleUnit.Degree, AngleUnit.Nanoradian) => new Angle((_value / 180 * Math.PI) / 1e-9d, AngleUnit.Nanoradian), + (AngleUnit.Degree, AngleUnit.NatoMil) => new Angle(_value * 160 / 9, AngleUnit.NatoMil), + (AngleUnit.Degree, AngleUnit.Radian) => new Angle(_value / 180 * Math.PI, AngleUnit.Radian), + (AngleUnit.Degree, AngleUnit.Revolution) => new Angle(_value / 360, AngleUnit.Revolution), + (AngleUnit.Degree, AngleUnit.Tilt) => new Angle(Math.Sin(_value / 180 * Math.PI), AngleUnit.Tilt), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AngleUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AngleUnit> IQuantity<AngleUnit>.ToUnit(AngleUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AngleUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Angle)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Angle)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Angle)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Angle)) + return this; + else if (conversionType == typeof(AngleUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Angle.Info; + else if (conversionType == typeof(BaseDimensions)) + return Angle.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Angle)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Angle/AngleUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Angle/AngleUnit.g.cs new file mode 100644 index 0000000000..20e4ff440e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Angle/AngleUnit.g.cs @@ -0,0 +1,47 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AngleUnit + { + Arcminute = 1, + Arcsecond = 2, + Centiradian = 3, + Deciradian = 4, + Degree = 5, + Gradian = 6, + Microdegree = 7, + Microradian = 8, + Millidegree = 9, + Milliradian = 10, + Nanodegree = 11, + Nanoradian = 12, + NatoMil = 13, + Radian = 14, + Revolution = 15, + Tilt = 16, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergy.csproj b/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergy.csproj new file mode 100644 index 0000000000..b80bf200f3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ApparentEnergy</Title> + <Description>Adds ApparentEnergy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>apparentenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{6f80e841-e953-bc39-6670-8711f2ad9d18}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ApparentEnergy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergy.g.cs b/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergy.g.cs new file mode 100644 index 0000000000..6326b0742e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergy.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct ApparentEnergy : IArithmeticQuantity<ApparentEnergy, ApparentEnergyUnit, double>, IEquatable<ApparentEnergy>, IComparable, IComparable<ApparentEnergy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ApparentEnergyUnit? _unit; + + static ApparentEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + BaseUnit = ApparentEnergyUnit.VoltampereHour; + Units = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast<ApparentEnergyUnit>().ToArray(); + Zero = new ApparentEnergy(0, BaseUnit); + Info = new QuantityInfo<ApparentEnergyUnit>("ApparentEnergy", + new UnitInfo<ApparentEnergyUnit>[] + { + new UnitInfo<ApparentEnergyUnit>(ApparentEnergyUnit.KilovoltampereHour, "KilovoltampereHours", BaseUnits.Undefined), + new UnitInfo<ApparentEnergyUnit>(ApparentEnergyUnit.MegavoltampereHour, "MegavoltampereHours", BaseUnits.Undefined), + new UnitInfo<ApparentEnergyUnit>(ApparentEnergyUnit.VoltampereHour, "VoltampereHours", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ApparentEnergy(double value, ApparentEnergyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ApparentEnergy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ApparentEnergyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ApparentEnergy, which is VoltampereHour. All conversions go via this value. + /// </summary> + public static ApparentEnergyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ApparentEnergy quantity. + /// </summary> + public static ApparentEnergyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. + /// </summary> + public static ApparentEnergy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ApparentEnergy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ApparentEnergyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ApparentEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentEnergyUnit.KilovoltampereHour"/> + /// </summary> + public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentEnergyUnit.MegavoltampereHour"/> + /// </summary> + public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentEnergyUnit.VoltampereHour"/> + /// </summary> + public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ApparentEnergyUnit -> BaseUnit + unitConverter.SetConversionFunction<ApparentEnergy>(ApparentEnergyUnit.KilovoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => quantity.ToUnit(ApparentEnergyUnit.VoltampereHour)); + unitConverter.SetConversionFunction<ApparentEnergy>(ApparentEnergyUnit.MegavoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => quantity.ToUnit(ApparentEnergyUnit.VoltampereHour)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ApparentEnergy>(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.VoltampereHour, quantity => quantity); + + // Register in unit converter: BaseUnit -> ApparentEnergyUnit + unitConverter.SetConversionFunction<ApparentEnergy>(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.KilovoltampereHour, quantity => quantity.ToUnit(ApparentEnergyUnit.KilovoltampereHour)); + unitConverter.SetConversionFunction<ApparentEnergy>(ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.MegavoltampereHour, quantity => quantity.ToUnit(ApparentEnergyUnit.MegavoltampereHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentEnergyUnit.KilovoltampereHour, new CultureInfo("en-US"), false, true, new string[]{"kVAh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentEnergyUnit.MegavoltampereHour, new CultureInfo("en-US"), false, true, new string[]{"MVAh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentEnergyUnit.VoltampereHour, new CultureInfo("en-US"), false, true, new string[]{"VAh"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ApparentEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ApparentEnergyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ApparentEnergy"/> from <see cref="ApparentEnergyUnit.KilovoltampereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) + { + double value = (double) kilovoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); + } + + /// <summary> + /// Creates a <see cref="ApparentEnergy"/> from <see cref="ApparentEnergyUnit.MegavoltampereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) + { + double value = (double) megavoltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); + } + + /// <summary> + /// Creates a <see cref="ApparentEnergy"/> from <see cref="ApparentEnergyUnit.VoltampereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) + { + double value = (double) voltamperehours; + return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ApparentEnergyUnit" /> to <see cref="ApparentEnergy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ApparentEnergy unit value.</returns> + public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) + { + return new ApparentEnergy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ApparentEnergy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ApparentEnergy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ApparentEnergy, ApparentEnergyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ApparentEnergy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ApparentEnergy result) + { + return QuantityParser.Default.TryParse<ApparentEnergy, ApparentEnergyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ApparentEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ApparentEnergyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ApparentEnergyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ApparentEnergyUnit)"/> + public static bool TryParseUnit(string str, out ApparentEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ApparentEnergyUnit unit) + { + return UnitParser.Default.TryParse<ApparentEnergyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ApparentEnergy operator -(ApparentEnergy right) + { + return new ApparentEnergy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ApparentEnergy"/> from adding two <see cref="ApparentEnergy"/>.</summary> + public static ApparentEnergy operator +(ApparentEnergy left, ApparentEnergy right) + { + return new ApparentEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ApparentEnergy"/> from subtracting two <see cref="ApparentEnergy"/>.</summary> + public static ApparentEnergy operator -(ApparentEnergy left, ApparentEnergy right) + { + return new ApparentEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ApparentEnergy"/> from multiplying value and <see cref="ApparentEnergy"/>.</summary> + public static ApparentEnergy operator *(double left, ApparentEnergy right) + { + return new ApparentEnergy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ApparentEnergy"/> from multiplying value and <see cref="ApparentEnergy"/>.</summary> + public static ApparentEnergy operator *(ApparentEnergy left, double right) + { + return new ApparentEnergy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ApparentEnergy"/> from dividing <see cref="ApparentEnergy"/> by value.</summary> + public static ApparentEnergy operator /(ApparentEnergy left, double right) + { + return new ApparentEnergy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ApparentEnergy"/> by <see cref="ApparentEnergy"/>.</summary> + public static double operator /(ApparentEnergy left, ApparentEnergy right) + { + return left.VoltampereHours / right.VoltampereHours; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ApparentEnergy left, ApparentEnergy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ApparentEnergy left, ApparentEnergy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ApparentEnergy left, ApparentEnergy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ApparentEnergy left, ApparentEnergy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ApparentEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ApparentEnergy left, ApparentEnergy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ApparentEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ApparentEnergy left, ApparentEnergy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ApparentEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ApparentEnergy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ApparentEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ApparentEnergy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ApparentEnergy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ApparentEnergy otherQuantity)) throw new ArgumentException("Expected type ApparentEnergy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ApparentEnergy"/> with another <see cref="ApparentEnergy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ApparentEnergy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ApparentEnergy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ApparentEnergy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ApparentEnergyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ApparentEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ApparentEnergy to another ApparentEnergy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ApparentEnergy with the specified unit.</returns> + public ApparentEnergy ToUnit(ApparentEnergyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ApparentEnergy"/> to another <see cref="ApparentEnergy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ApparentEnergy with the specified unit.</returns> + public ApparentEnergy ToUnit(ApparentEnergyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ApparentEnergy), Unit, typeof(ApparentEnergy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ApparentEnergy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ApparentEnergy"/> to another <see cref="ApparentEnergy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ApparentEnergy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ApparentEnergyUnit unit, [NotNullWhen(true)] out ApparentEnergy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ApparentEnergy? convertedOrNull = (Unit, unit) switch + { + // ApparentEnergyUnit -> BaseUnit + (ApparentEnergyUnit.KilovoltampereHour, ApparentEnergyUnit.VoltampereHour) => new ApparentEnergy((_value) * 1e3d, ApparentEnergyUnit.VoltampereHour), + (ApparentEnergyUnit.MegavoltampereHour, ApparentEnergyUnit.VoltampereHour) => new ApparentEnergy((_value) * 1e6d, ApparentEnergyUnit.VoltampereHour), + + // BaseUnit -> ApparentEnergyUnit + (ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.KilovoltampereHour) => new ApparentEnergy((_value) / 1e3d, ApparentEnergyUnit.KilovoltampereHour), + (ApparentEnergyUnit.VoltampereHour, ApparentEnergyUnit.MegavoltampereHour) => new ApparentEnergy((_value) / 1e6d, ApparentEnergyUnit.MegavoltampereHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ApparentEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ApparentEnergyUnit> IQuantity<ApparentEnergyUnit>.ToUnit(ApparentEnergyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ApparentEnergyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ApparentEnergy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ApparentEnergy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ApparentEnergy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ApparentEnergy)) + return this; + else if (conversionType == typeof(ApparentEnergyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ApparentEnergy.Info; + else if (conversionType == typeof(BaseDimensions)) + return ApparentEnergy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ApparentEnergy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergyUnit.g.cs new file mode 100644 index 0000000000..2a8c1aba5b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ApparentEnergy/ApparentEnergyUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ApparentEnergyUnit + { + KilovoltampereHour = 1, + MegavoltampereHour = 2, + VoltampereHour = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPower.csproj b/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPower.csproj new file mode 100644 index 0000000000..40d7bed2e5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPower.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ApparentPower</Title> + <Description>Adds ApparentPower units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>apparentpower unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{88b9a61a-b21b-97cc-ef89-78d1e3ff7767}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ApparentPower</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPower.g.cs b/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPower.g.cs new file mode 100644 index 0000000000..bfe60bb282 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPower.g.cs @@ -0,0 +1,901 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct ApparentPower : IArithmeticQuantity<ApparentPower, ApparentPowerUnit, double>, IEquatable<ApparentPower>, IComparable, IComparable<ApparentPower>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ApparentPowerUnit? _unit; + + static ApparentPower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + BaseUnit = ApparentPowerUnit.Voltampere; + Units = Enum.GetValues(typeof(ApparentPowerUnit)).Cast<ApparentPowerUnit>().ToArray(); + Zero = new ApparentPower(0, BaseUnit); + Info = new QuantityInfo<ApparentPowerUnit>("ApparentPower", + new UnitInfo<ApparentPowerUnit>[] + { + new UnitInfo<ApparentPowerUnit>(ApparentPowerUnit.Gigavoltampere, "Gigavoltamperes", BaseUnits.Undefined), + new UnitInfo<ApparentPowerUnit>(ApparentPowerUnit.Kilovoltampere, "Kilovoltamperes", BaseUnits.Undefined), + new UnitInfo<ApparentPowerUnit>(ApparentPowerUnit.Megavoltampere, "Megavoltamperes", BaseUnits.Undefined), + new UnitInfo<ApparentPowerUnit>(ApparentPowerUnit.Voltampere, "Voltamperes", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ApparentPower(double value, ApparentPowerUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ApparentPower" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ApparentPowerUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ApparentPower, which is Voltampere. All conversions go via this value. + /// </summary> + public static ApparentPowerUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ApparentPower quantity. + /// </summary> + public static ApparentPowerUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. + /// </summary> + public static ApparentPower Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ApparentPower AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ApparentPowerUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ApparentPower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentPowerUnit.Gigavoltampere"/> + /// </summary> + public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentPowerUnit.Kilovoltampere"/> + /// </summary> + public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentPowerUnit.Megavoltampere"/> + /// </summary> + public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ApparentPowerUnit.Voltampere"/> + /// </summary> + public double Voltamperes => As(ApparentPowerUnit.Voltampere); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ApparentPowerUnit -> BaseUnit + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Gigavoltampere, ApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Voltampere)); + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Kilovoltampere, ApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Voltampere)); + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Megavoltampere, ApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Voltampere)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Voltampere, quantity => quantity); + + // Register in unit converter: BaseUnit -> ApparentPowerUnit + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Gigavoltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Gigavoltampere)); + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Kilovoltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Kilovoltampere)); + unitConverter.SetConversionFunction<ApparentPower>(ApparentPowerUnit.Voltampere, ApparentPowerUnit.Megavoltampere, quantity => quantity.ToUnit(ApparentPowerUnit.Megavoltampere)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentPowerUnit.Gigavoltampere, new CultureInfo("en-US"), false, true, new string[]{"GVA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentPowerUnit.Kilovoltampere, new CultureInfo("en-US"), false, true, new string[]{"kVA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentPowerUnit.Megavoltampere, new CultureInfo("en-US"), false, true, new string[]{"MVA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ApparentPowerUnit.Voltampere, new CultureInfo("en-US"), false, true, new string[]{"VA"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ApparentPowerUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ApparentPowerUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ApparentPower"/> from <see cref="ApparentPowerUnit.Gigavoltampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) + { + double value = (double) gigavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); + } + + /// <summary> + /// Creates a <see cref="ApparentPower"/> from <see cref="ApparentPowerUnit.Kilovoltampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) + { + double value = (double) kilovoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); + } + + /// <summary> + /// Creates a <see cref="ApparentPower"/> from <see cref="ApparentPowerUnit.Megavoltampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) + { + double value = (double) megavoltamperes; + return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); + } + + /// <summary> + /// Creates a <see cref="ApparentPower"/> from <see cref="ApparentPowerUnit.Voltampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ApparentPower FromVoltamperes(QuantityValue voltamperes) + { + double value = (double) voltamperes; + return new ApparentPower(value, ApparentPowerUnit.Voltampere); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ApparentPowerUnit" /> to <see cref="ApparentPower" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ApparentPower unit value.</returns> + public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) + { + return new ApparentPower((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ApparentPower Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ApparentPower Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ApparentPower, ApparentPowerUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ApparentPower result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ApparentPower result) + { + return QuantityParser.Default.TryParse<ApparentPower, ApparentPowerUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ApparentPowerUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ApparentPowerUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ApparentPowerUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ApparentPowerUnit)"/> + public static bool TryParseUnit(string str, out ApparentPowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ApparentPowerUnit unit) + { + return UnitParser.Default.TryParse<ApparentPowerUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ApparentPower operator -(ApparentPower right) + { + return new ApparentPower(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ApparentPower"/> from adding two <see cref="ApparentPower"/>.</summary> + public static ApparentPower operator +(ApparentPower left, ApparentPower right) + { + return new ApparentPower(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ApparentPower"/> from subtracting two <see cref="ApparentPower"/>.</summary> + public static ApparentPower operator -(ApparentPower left, ApparentPower right) + { + return new ApparentPower(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ApparentPower"/> from multiplying value and <see cref="ApparentPower"/>.</summary> + public static ApparentPower operator *(double left, ApparentPower right) + { + return new ApparentPower(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ApparentPower"/> from multiplying value and <see cref="ApparentPower"/>.</summary> + public static ApparentPower operator *(ApparentPower left, double right) + { + return new ApparentPower(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ApparentPower"/> from dividing <see cref="ApparentPower"/> by value.</summary> + public static ApparentPower operator /(ApparentPower left, double right) + { + return new ApparentPower(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ApparentPower"/> by <see cref="ApparentPower"/>.</summary> + public static double operator /(ApparentPower left, ApparentPower right) + { + return left.Voltamperes / right.Voltamperes; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ApparentPower left, ApparentPower right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ApparentPower left, ApparentPower right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ApparentPower left, ApparentPower right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ApparentPower left, ApparentPower right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ApparentPower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentPower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ApparentPower left, ApparentPower right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ApparentPower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentPower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ApparentPower left, ApparentPower right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ApparentPower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentPower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ApparentPower otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ApparentPower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ApparentPower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ApparentPower other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ApparentPower"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ApparentPower otherQuantity)) throw new ArgumentException("Expected type ApparentPower.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ApparentPower"/> with another <see cref="ApparentPower"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ApparentPower other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ApparentPower within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ApparentPower.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ApparentPowerUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ApparentPowerUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ApparentPower to another ApparentPower with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ApparentPower with the specified unit.</returns> + public ApparentPower ToUnit(ApparentPowerUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ApparentPower"/> to another <see cref="ApparentPower"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ApparentPower with the specified unit.</returns> + public ApparentPower ToUnit(ApparentPowerUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ApparentPower), Unit, typeof(ApparentPower), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ApparentPower)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ApparentPower"/> to another <see cref="ApparentPower"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ApparentPower"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ApparentPowerUnit unit, [NotNullWhen(true)] out ApparentPower? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ApparentPower? convertedOrNull = (Unit, unit) switch + { + // ApparentPowerUnit -> BaseUnit + (ApparentPowerUnit.Gigavoltampere, ApparentPowerUnit.Voltampere) => new ApparentPower((_value) * 1e9d, ApparentPowerUnit.Voltampere), + (ApparentPowerUnit.Kilovoltampere, ApparentPowerUnit.Voltampere) => new ApparentPower((_value) * 1e3d, ApparentPowerUnit.Voltampere), + (ApparentPowerUnit.Megavoltampere, ApparentPowerUnit.Voltampere) => new ApparentPower((_value) * 1e6d, ApparentPowerUnit.Voltampere), + + // BaseUnit -> ApparentPowerUnit + (ApparentPowerUnit.Voltampere, ApparentPowerUnit.Gigavoltampere) => new ApparentPower((_value) / 1e9d, ApparentPowerUnit.Gigavoltampere), + (ApparentPowerUnit.Voltampere, ApparentPowerUnit.Kilovoltampere) => new ApparentPower((_value) / 1e3d, ApparentPowerUnit.Kilovoltampere), + (ApparentPowerUnit.Voltampere, ApparentPowerUnit.Megavoltampere) => new ApparentPower((_value) / 1e6d, ApparentPowerUnit.Megavoltampere), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ApparentPowerUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ApparentPowerUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ApparentPowerUnit> IQuantity<ApparentPowerUnit>.ToUnit(ApparentPowerUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ApparentPowerUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ApparentPower)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ApparentPower)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ApparentPower)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ApparentPower)) + return this; + else if (conversionType == typeof(ApparentPowerUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ApparentPower.Info; + else if (conversionType == typeof(BaseDimensions)) + return ApparentPower.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ApparentPower)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPowerUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPowerUnit.g.cs new file mode 100644 index 0000000000..358388af5f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ApparentPower/ApparentPowerUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ApparentPowerUnit + { + Gigavoltampere = 1, + Kilovoltampere = 2, + Megavoltampere = 3, + Voltampere = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Area/Area.csproj b/UnitsNet.Modular/GeneratedCode/Area/Area.csproj new file mode 100644 index 0000000000..6256cfce48 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Area/Area.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Area</Title> + <Description>Adds Area units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>area unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{04c24d02-bad7-a877-ff9b-a36a886c9633}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Area</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Area/Area.g.cs b/UnitsNet.Modular/GeneratedCode/Area/Area.g.cs new file mode 100644 index 0000000000..8d21a8b135 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Area/Area.g.cs @@ -0,0 +1,1138 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct Area : IArithmeticQuantity<Area, AreaUnit, double>, IEquatable<Area>, IComparable, IComparable<Area>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AreaUnit? _unit; + + static Area() + { + BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + BaseUnit = AreaUnit.SquareMeter; + Units = Enum.GetValues(typeof(AreaUnit)).Cast<AreaUnit>().ToArray(); + Zero = new Area(0, BaseUnit); + Info = new QuantityInfo<AreaUnit>("Area", + new UnitInfo<AreaUnit>[] + { + new UnitInfo<AreaUnit>(AreaUnit.Acre, "Acres", BaseUnits.Undefined), + new UnitInfo<AreaUnit>(AreaUnit.Hectare, "Hectares", BaseUnits.Undefined), + new UnitInfo<AreaUnit>(AreaUnit.SquareCentimeter, "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter)), + new UnitInfo<AreaUnit>(AreaUnit.SquareDecimeter, "SquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter)), + new UnitInfo<AreaUnit>(AreaUnit.SquareFoot, "SquareFeet", new BaseUnits(length: LengthUnit.Foot)), + new UnitInfo<AreaUnit>(AreaUnit.SquareInch, "SquareInches", new BaseUnits(length: LengthUnit.Inch)), + new UnitInfo<AreaUnit>(AreaUnit.SquareKilometer, "SquareKilometers", new BaseUnits(length: LengthUnit.Kilometer)), + new UnitInfo<AreaUnit>(AreaUnit.SquareMeter, "SquareMeters", new BaseUnits(length: LengthUnit.Meter)), + new UnitInfo<AreaUnit>(AreaUnit.SquareMicrometer, "SquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer)), + new UnitInfo<AreaUnit>(AreaUnit.SquareMile, "SquareMiles", new BaseUnits(length: LengthUnit.Mile)), + new UnitInfo<AreaUnit>(AreaUnit.SquareMillimeter, "SquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter)), + new UnitInfo<AreaUnit>(AreaUnit.SquareNauticalMile, "SquareNauticalMiles", BaseUnits.Undefined), + new UnitInfo<AreaUnit>(AreaUnit.SquareYard, "SquareYards", new BaseUnits(length: LengthUnit.Yard)), + new UnitInfo<AreaUnit>(AreaUnit.UsSurveySquareFoot, "UsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Area(double value, AreaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Area" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AreaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Area, which is SquareMeter. All conversions go via this value. + /// </summary> + public static AreaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Area quantity. + /// </summary> + public static AreaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. + /// </summary> + public static Area Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Area AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AreaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Area.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.Acre"/> + /// </summary> + public double Acres => As(AreaUnit.Acre); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.Hectare"/> + /// </summary> + public double Hectares => As(AreaUnit.Hectare); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareCentimeter"/> + /// </summary> + public double SquareCentimeters => As(AreaUnit.SquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareDecimeter"/> + /// </summary> + public double SquareDecimeters => As(AreaUnit.SquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareFoot"/> + /// </summary> + public double SquareFeet => As(AreaUnit.SquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareInch"/> + /// </summary> + public double SquareInches => As(AreaUnit.SquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareKilometer"/> + /// </summary> + public double SquareKilometers => As(AreaUnit.SquareKilometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareMeter"/> + /// </summary> + public double SquareMeters => As(AreaUnit.SquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareMicrometer"/> + /// </summary> + public double SquareMicrometers => As(AreaUnit.SquareMicrometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareMile"/> + /// </summary> + public double SquareMiles => As(AreaUnit.SquareMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareMillimeter"/> + /// </summary> + public double SquareMillimeters => As(AreaUnit.SquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareNauticalMile"/> + /// </summary> + public double SquareNauticalMiles => As(AreaUnit.SquareNauticalMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.SquareYard"/> + /// </summary> + public double SquareYards => As(AreaUnit.SquareYard); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaUnit.UsSurveySquareFoot"/> + /// </summary> + public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AreaUnit -> BaseUnit + unitConverter.SetConversionFunction<Area>(AreaUnit.Acre, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.Hectare, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareCentimeter, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareDecimeter, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareFoot, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareInch, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareKilometer, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMicrometer, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMile, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMillimeter, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareNauticalMile, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareYard, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.UsSurveySquareFoot, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> AreaUnit + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.Acre, quantity => quantity.ToUnit(AreaUnit.Acre)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.Hectare, quantity => quantity.ToUnit(AreaUnit.Hectare)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareCentimeter, quantity => quantity.ToUnit(AreaUnit.SquareCentimeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareDecimeter, quantity => quantity.ToUnit(AreaUnit.SquareDecimeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareFoot, quantity => quantity.ToUnit(AreaUnit.SquareFoot)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareInch, quantity => quantity.ToUnit(AreaUnit.SquareInch)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareKilometer, quantity => quantity.ToUnit(AreaUnit.SquareKilometer)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareMicrometer, quantity => quantity.ToUnit(AreaUnit.SquareMicrometer)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareMile, quantity => quantity.ToUnit(AreaUnit.SquareMile)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareMillimeter, quantity => quantity.ToUnit(AreaUnit.SquareMillimeter)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareNauticalMile, quantity => quantity.ToUnit(AreaUnit.SquareNauticalMile)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.SquareYard, quantity => quantity.ToUnit(AreaUnit.SquareYard)); + unitConverter.SetConversionFunction<Area>(AreaUnit.SquareMeter, AreaUnit.UsSurveySquareFoot, quantity => quantity.ToUnit(AreaUnit.UsSurveySquareFoot)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.Acre, new CultureInfo("en-US"), false, true, new string[]{"ac"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.Acre, new CultureInfo("ru-RU"), false, true, new string[]{"акр"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.Acre, new CultureInfo("zh-CN"), false, true, new string[]{"英亩"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.Hectare, new CultureInfo("en-US"), false, true, new string[]{"ha"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.Hectare, new CultureInfo("ru-RU"), false, true, new string[]{"га"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.Hectare, new CultureInfo("zh-CN"), false, true, new string[]{"英亩"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"см²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareCentimeter, new CultureInfo("zh-CN"), false, true, new string[]{"平方厘米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareDecimeter, new CultureInfo("ru-RU"), false, true, new string[]{"дм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareDecimeter, new CultureInfo("zh-CN"), false, true, new string[]{"平方分米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareFoot, new CultureInfo("en-US"), false, true, new string[]{"ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareFoot, new CultureInfo("ru-RU"), false, true, new string[]{"фут²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareFoot, new CultureInfo("zh-CN"), false, true, new string[]{"平方英尺"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareInch, new CultureInfo("en-US"), false, true, new string[]{"in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareInch, new CultureInfo("ru-RU"), false, true, new string[]{"дюйм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareInch, new CultureInfo("zh-CN"), false, true, new string[]{"平方英寸"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareKilometer, new CultureInfo("en-US"), false, true, new string[]{"km²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareKilometer, new CultureInfo("ru-RU"), false, true, new string[]{"км²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareKilometer, new CultureInfo("zh-CN"), false, true, new string[]{"平方公里"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMeter, new CultureInfo("en-US"), false, true, new string[]{"m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMeter, new CultureInfo("ru-RU"), false, true, new string[]{"м²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMeter, new CultureInfo("zh-CN"), false, true, new string[]{"平方米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMicrometer, new CultureInfo("en-US"), false, true, new string[]{"µm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMicrometer, new CultureInfo("ru-RU"), false, true, new string[]{"мкм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMicrometer, new CultureInfo("zh-CN"), false, true, new string[]{"平方微米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMile, new CultureInfo("en-US"), false, true, new string[]{"mi²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMile, new CultureInfo("ru-RU"), false, true, new string[]{"миля²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMile, new CultureInfo("zh-CN"), false, true, new string[]{"平方英里"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"мм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareMillimeter, new CultureInfo("zh-CN"), false, true, new string[]{"平方毫米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareNauticalMile, new CultureInfo("en-US"), false, true, new string[]{"nmi²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareNauticalMile, new CultureInfo("ru-RU"), false, true, new string[]{"морск.миля²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareNauticalMile, new CultureInfo("zh-CN"), false, true, new string[]{"平方海里"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareYard, new CultureInfo("en-US"), false, true, new string[]{"yd²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareYard, new CultureInfo("ru-RU"), false, true, new string[]{"ярд²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.SquareYard, new CultureInfo("zh-CN"), false, true, new string[]{"平方码"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.UsSurveySquareFoot, new CultureInfo("en-US"), false, true, new string[]{"ft² (US)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaUnit.UsSurveySquareFoot, new CultureInfo("ru-RU"), false, true, new string[]{"фут² (US)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AreaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AreaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.Acre"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromAcres(QuantityValue acres) + { + double value = (double) acres; + return new Area(value, AreaUnit.Acre); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.Hectare"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromHectares(QuantityValue hectares) + { + double value = (double) hectares; + return new Area(value, AreaUnit.Hectare); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareCentimeters(QuantityValue squarecentimeters) + { + double value = (double) squarecentimeters; + return new Area(value, AreaUnit.SquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareDecimeters(QuantityValue squaredecimeters) + { + double value = (double) squaredecimeters; + return new Area(value, AreaUnit.SquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareFeet(QuantityValue squarefeet) + { + double value = (double) squarefeet; + return new Area(value, AreaUnit.SquareFoot); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareInches(QuantityValue squareinches) + { + double value = (double) squareinches; + return new Area(value, AreaUnit.SquareInch); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareKilometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareKilometers(QuantityValue squarekilometers) + { + double value = (double) squarekilometers; + return new Area(value, AreaUnit.SquareKilometer); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareMeters(QuantityValue squaremeters) + { + double value = (double) squaremeters; + return new Area(value, AreaUnit.SquareMeter); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareMicrometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareMicrometers(QuantityValue squaremicrometers) + { + double value = (double) squaremicrometers; + return new Area(value, AreaUnit.SquareMicrometer); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareMiles(QuantityValue squaremiles) + { + double value = (double) squaremiles; + return new Area(value, AreaUnit.SquareMile); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareMillimeters(QuantityValue squaremillimeters) + { + double value = (double) squaremillimeters; + return new Area(value, AreaUnit.SquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareNauticalMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareNauticalMiles(QuantityValue squarenauticalmiles) + { + double value = (double) squarenauticalmiles; + return new Area(value, AreaUnit.SquareNauticalMile); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.SquareYard"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromSquareYards(QuantityValue squareyards) + { + double value = (double) squareyards; + return new Area(value, AreaUnit.SquareYard); + } + + /// <summary> + /// Creates a <see cref="Area"/> from <see cref="AreaUnit.UsSurveySquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) + { + double value = (double) ussurveysquarefeet; + return new Area(value, AreaUnit.UsSurveySquareFoot); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AreaUnit" /> to <see cref="Area" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Area unit value.</returns> + public static Area From(QuantityValue value, AreaUnit fromUnit) + { + return new Area((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Area Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Area Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Area, AreaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Area result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Area result) + { + return QuantityParser.Default.TryParse<Area, AreaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AreaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AreaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AreaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AreaUnit)"/> + public static bool TryParseUnit(string str, out AreaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaUnit unit) + { + return UnitParser.Default.TryParse<AreaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Area operator -(Area right) + { + return new Area(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Area"/> from adding two <see cref="Area"/>.</summary> + public static Area operator +(Area left, Area right) + { + return new Area(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Area"/> from subtracting two <see cref="Area"/>.</summary> + public static Area operator -(Area left, Area right) + { + return new Area(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Area"/> from multiplying value and <see cref="Area"/>.</summary> + public static Area operator *(double left, Area right) + { + return new Area(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Area"/> from multiplying value and <see cref="Area"/>.</summary> + public static Area operator *(Area left, double right) + { + return new Area(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Area"/> from dividing <see cref="Area"/> by value.</summary> + public static Area operator /(Area left, double right) + { + return new Area(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Area"/> by <see cref="Area"/>.</summary> + public static double operator /(Area left, Area right) + { + return left.SquareMeters / right.SquareMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Area left, Area right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Area left, Area right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Area left, Area right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Area left, Area right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Area"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Area, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Area left, Area right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Area"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Area, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Area left, Area right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Area"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Area, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Area otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Area"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Area, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Area other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Area"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Area otherQuantity)) throw new ArgumentException("Expected type Area.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Area"/> with another <see cref="Area"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Area other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Area within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Area.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AreaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AreaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Area to another Area with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Area with the specified unit.</returns> + public Area ToUnit(AreaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Area"/> to another <see cref="Area"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Area with the specified unit.</returns> + public Area ToUnit(AreaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Area), Unit, typeof(Area), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Area)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Area"/> to another <see cref="Area"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Area"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AreaUnit unit, [NotNullWhen(true)] out Area? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Area? convertedOrNull = (Unit, unit) switch + { + // AreaUnit -> BaseUnit + (AreaUnit.Acre, AreaUnit.SquareMeter) => new Area(_value * 4046.85642, AreaUnit.SquareMeter), + (AreaUnit.Hectare, AreaUnit.SquareMeter) => new Area(_value * 1e4, AreaUnit.SquareMeter), + (AreaUnit.SquareCentimeter, AreaUnit.SquareMeter) => new Area(_value * 1e-4, AreaUnit.SquareMeter), + (AreaUnit.SquareDecimeter, AreaUnit.SquareMeter) => new Area(_value * 1e-2, AreaUnit.SquareMeter), + (AreaUnit.SquareFoot, AreaUnit.SquareMeter) => new Area(_value * 9.290304e-2, AreaUnit.SquareMeter), + (AreaUnit.SquareInch, AreaUnit.SquareMeter) => new Area(_value * 0.00064516, AreaUnit.SquareMeter), + (AreaUnit.SquareKilometer, AreaUnit.SquareMeter) => new Area(_value * 1e6, AreaUnit.SquareMeter), + (AreaUnit.SquareMicrometer, AreaUnit.SquareMeter) => new Area(_value * 1e-12, AreaUnit.SquareMeter), + (AreaUnit.SquareMile, AreaUnit.SquareMeter) => new Area(_value * 2.59e6, AreaUnit.SquareMeter), + (AreaUnit.SquareMillimeter, AreaUnit.SquareMeter) => new Area(_value * 1e-6, AreaUnit.SquareMeter), + (AreaUnit.SquareNauticalMile, AreaUnit.SquareMeter) => new Area(_value * 3429904, AreaUnit.SquareMeter), + (AreaUnit.SquareYard, AreaUnit.SquareMeter) => new Area(_value * 0.836127, AreaUnit.SquareMeter), + (AreaUnit.UsSurveySquareFoot, AreaUnit.SquareMeter) => new Area(_value * 0.09290341161, AreaUnit.SquareMeter), + + // BaseUnit -> AreaUnit + (AreaUnit.SquareMeter, AreaUnit.Acre) => new Area(_value / 4046.85642, AreaUnit.Acre), + (AreaUnit.SquareMeter, AreaUnit.Hectare) => new Area(_value / 1e4, AreaUnit.Hectare), + (AreaUnit.SquareMeter, AreaUnit.SquareCentimeter) => new Area(_value / 1e-4, AreaUnit.SquareCentimeter), + (AreaUnit.SquareMeter, AreaUnit.SquareDecimeter) => new Area(_value / 1e-2, AreaUnit.SquareDecimeter), + (AreaUnit.SquareMeter, AreaUnit.SquareFoot) => new Area(_value / 9.290304e-2, AreaUnit.SquareFoot), + (AreaUnit.SquareMeter, AreaUnit.SquareInch) => new Area(_value / 0.00064516, AreaUnit.SquareInch), + (AreaUnit.SquareMeter, AreaUnit.SquareKilometer) => new Area(_value / 1e6, AreaUnit.SquareKilometer), + (AreaUnit.SquareMeter, AreaUnit.SquareMicrometer) => new Area(_value / 1e-12, AreaUnit.SquareMicrometer), + (AreaUnit.SquareMeter, AreaUnit.SquareMile) => new Area(_value / 2.59e6, AreaUnit.SquareMile), + (AreaUnit.SquareMeter, AreaUnit.SquareMillimeter) => new Area(_value / 1e-6, AreaUnit.SquareMillimeter), + (AreaUnit.SquareMeter, AreaUnit.SquareNauticalMile) => new Area(_value / 3429904, AreaUnit.SquareNauticalMile), + (AreaUnit.SquareMeter, AreaUnit.SquareYard) => new Area(_value / 0.836127, AreaUnit.SquareYard), + (AreaUnit.SquareMeter, AreaUnit.UsSurveySquareFoot) => new Area(_value / 0.09290341161, AreaUnit.UsSurveySquareFoot), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AreaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AreaUnit> IQuantity<AreaUnit>.ToUnit(AreaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AreaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Area)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Area)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Area)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Area)) + return this; + else if (conversionType == typeof(AreaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Area.Info; + else if (conversionType == typeof(BaseDimensions)) + return Area.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Area)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Area/AreaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Area/AreaUnit.g.cs new file mode 100644 index 0000000000..f0320c4e99 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Area/AreaUnit.g.cs @@ -0,0 +1,45 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AreaUnit + { + Acre = 1, + Hectare = 2, + SquareCentimeter = 3, + SquareDecimeter = 4, + SquareFoot = 5, + SquareInch = 6, + SquareKilometer = 7, + SquareMeter = 8, + SquareMicrometer = 9, + SquareMile = 10, + SquareMillimeter = 11, + SquareNauticalMile = 12, + SquareYard = 13, + UsSurveySquareFoot = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensity.csproj b/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensity.csproj new file mode 100644 index 0000000000..d6599301d6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET AreaDensity</Title> + <Description>Adds AreaDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>areadensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{92ff1332-bf34-943e-a58d-8a76746d879e}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.AreaDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensity.g.cs b/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensity.g.cs new file mode 100644 index 0000000000..9380445710 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensity.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The area density of a two-dimensional object is calculated as the mass per unit area. For paper this is also called grammage. + /// </summary> + [DataContract] + public readonly partial struct AreaDensity : IArithmeticQuantity<AreaDensity, AreaDensityUnit, double>, IEquatable<AreaDensity>, IComparable, IComparable<AreaDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AreaDensityUnit? _unit; + + static AreaDensity() + { + BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); + BaseUnit = AreaDensityUnit.KilogramPerSquareMeter; + Units = Enum.GetValues(typeof(AreaDensityUnit)).Cast<AreaDensityUnit>().ToArray(); + Zero = new AreaDensity(0, BaseUnit); + Info = new QuantityInfo<AreaDensityUnit>("AreaDensity", + new UnitInfo<AreaDensityUnit>[] + { + new UnitInfo<AreaDensityUnit>(AreaDensityUnit.GramPerSquareMeter, "GramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)), + new UnitInfo<AreaDensityUnit>(AreaDensityUnit.KilogramPerSquareMeter, "KilogramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)), + new UnitInfo<AreaDensityUnit>(AreaDensityUnit.MilligramPerSquareMeter, "MilligramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public AreaDensity(double value, AreaDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="AreaDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AreaDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. + /// </summary> + public static AreaDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the AreaDensity quantity. + /// </summary> + public static AreaDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. + /// </summary> + public static AreaDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static AreaDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AreaDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => AreaDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaDensityUnit.GramPerSquareMeter"/> + /// </summary> + public double GramsPerSquareMeter => As(AreaDensityUnit.GramPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaDensityUnit.KilogramPerSquareMeter"/> + /// </summary> + public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaDensityUnit.MilligramPerSquareMeter"/> + /// </summary> + public double MilligramsPerSquareMeter => As(AreaDensityUnit.MilligramPerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AreaDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<AreaDensity>(AreaDensityUnit.GramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.KilogramPerSquareMeter)); + unitConverter.SetConversionFunction<AreaDensity>(AreaDensityUnit.MilligramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.KilogramPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<AreaDensity>(AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> AreaDensityUnit + unitConverter.SetConversionFunction<AreaDensity>(AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.GramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.GramPerSquareMeter)); + unitConverter.SetConversionFunction<AreaDensity>(AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.MilligramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.MilligramPerSquareMeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AreaDensityUnit.GramPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"g/m²", "gsm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaDensityUnit.KilogramPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kg/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaDensityUnit.MilligramPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"mg/m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AreaDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AreaDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="AreaDensity"/> from <see cref="AreaDensityUnit.GramPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaDensity FromGramsPerSquareMeter(QuantityValue gramspersquaremeter) + { + double value = (double) gramspersquaremeter; + return new AreaDensity(value, AreaDensityUnit.GramPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="AreaDensity"/> from <see cref="AreaDensityUnit.KilogramPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) + { + double value = (double) kilogramspersquaremeter; + return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="AreaDensity"/> from <see cref="AreaDensityUnit.MilligramPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaDensity FromMilligramsPerSquareMeter(QuantityValue milligramspersquaremeter) + { + double value = (double) milligramspersquaremeter; + return new AreaDensity(value, AreaDensityUnit.MilligramPerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AreaDensityUnit" /> to <see cref="AreaDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>AreaDensity unit value.</returns> + public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) + { + return new AreaDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static AreaDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static AreaDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<AreaDensity, AreaDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out AreaDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out AreaDensity result) + { + return QuantityParser.Default.TryParse<AreaDensity, AreaDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AreaDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AreaDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AreaDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AreaDensityUnit)"/> + public static bool TryParseUnit(string str, out AreaDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaDensityUnit unit) + { + return UnitParser.Default.TryParse<AreaDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static AreaDensity operator -(AreaDensity right) + { + return new AreaDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="AreaDensity"/> from adding two <see cref="AreaDensity"/>.</summary> + public static AreaDensity operator +(AreaDensity left, AreaDensity right) + { + return new AreaDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="AreaDensity"/> from subtracting two <see cref="AreaDensity"/>.</summary> + public static AreaDensity operator -(AreaDensity left, AreaDensity right) + { + return new AreaDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="AreaDensity"/> from multiplying value and <see cref="AreaDensity"/>.</summary> + public static AreaDensity operator *(double left, AreaDensity right) + { + return new AreaDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="AreaDensity"/> from multiplying value and <see cref="AreaDensity"/>.</summary> + public static AreaDensity operator *(AreaDensity left, double right) + { + return new AreaDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="AreaDensity"/> from dividing <see cref="AreaDensity"/> by value.</summary> + public static AreaDensity operator /(AreaDensity left, double right) + { + return new AreaDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="AreaDensity"/> by <see cref="AreaDensity"/>.</summary> + public static double operator /(AreaDensity left, AreaDensity right) + { + return left.KilogramsPerSquareMeter / right.KilogramsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(AreaDensity left, AreaDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(AreaDensity left, AreaDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(AreaDensity left, AreaDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(AreaDensity left, AreaDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="AreaDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(AreaDensity left, AreaDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="AreaDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(AreaDensity left, AreaDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AreaDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is AreaDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AreaDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(AreaDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="AreaDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is AreaDensity otherQuantity)) throw new ArgumentException("Expected type AreaDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="AreaDensity"/> with another <see cref="AreaDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(AreaDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another AreaDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current AreaDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AreaDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AreaDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this AreaDensity to another AreaDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A AreaDensity with the specified unit.</returns> + public AreaDensity ToUnit(AreaDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="AreaDensity"/> to another <see cref="AreaDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A AreaDensity with the specified unit.</returns> + public AreaDensity ToUnit(AreaDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(AreaDensity), Unit, typeof(AreaDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (AreaDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="AreaDensity"/> to another <see cref="AreaDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="AreaDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AreaDensityUnit unit, [NotNullWhen(true)] out AreaDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + AreaDensity? convertedOrNull = (Unit, unit) switch + { + // AreaDensityUnit -> BaseUnit + (AreaDensityUnit.GramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter) => new AreaDensity(_value / 1000, AreaDensityUnit.KilogramPerSquareMeter), + (AreaDensityUnit.MilligramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter) => new AreaDensity(_value / 1000000, AreaDensityUnit.KilogramPerSquareMeter), + + // BaseUnit -> AreaDensityUnit + (AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.GramPerSquareMeter) => new AreaDensity(_value * 1000, AreaDensityUnit.GramPerSquareMeter), + (AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.MilligramPerSquareMeter) => new AreaDensity(_value * 1000000, AreaDensityUnit.MilligramPerSquareMeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AreaDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AreaDensityUnit> IQuantity<AreaDensityUnit>.ToUnit(AreaDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AreaDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AreaDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AreaDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AreaDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(AreaDensity)) + return this; + else if (conversionType == typeof(AreaDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return AreaDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return AreaDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(AreaDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensityUnit.g.cs new file mode 100644 index 0000000000..bacdc7e8f4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AreaDensity/AreaDensityUnit.g.cs @@ -0,0 +1,39 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AreaDensityUnit + { + + /// <summary> + /// Also known as grammage for paper industry. In fiber industry used with abbreviation 'gsm'. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Grammage</remarks> + GramPerSquareMeter = 6, + KilogramPerSquareMeter = 1, + MilligramPerSquareMeter = 10, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertia.csproj b/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertia.csproj new file mode 100644 index 0000000000..3ba5cc0d4b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertia.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET AreaMomentOfInertia</Title> + <Description>Adds AreaMomentOfInertia units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>areamomentofinertia unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{566ef13c-0d17-e465-d35f-1bd9c65559bf}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.AreaMomentOfInertia</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertia.g.cs b/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertia.g.cs new file mode 100644 index 0000000000..ff16794a02 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertia.g.cs @@ -0,0 +1,943 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// A geometric property of an area that reflects how its points are distributed with regard to an axis. + /// </summary> + [DataContract] + public readonly partial struct AreaMomentOfInertia : IArithmeticQuantity<AreaMomentOfInertia, AreaMomentOfInertiaUnit, double>, IEquatable<AreaMomentOfInertia>, IComparable, IComparable<AreaMomentOfInertia>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly AreaMomentOfInertiaUnit? _unit; + + static AreaMomentOfInertia() + { + BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); + BaseUnit = AreaMomentOfInertiaUnit.MeterToTheFourth; + Units = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast<AreaMomentOfInertiaUnit>().ToArray(); + Zero = new AreaMomentOfInertia(0, BaseUnit); + Info = new QuantityInfo<AreaMomentOfInertiaUnit>("AreaMomentOfInertia", + new UnitInfo<AreaMomentOfInertiaUnit>[] + { + new UnitInfo<AreaMomentOfInertiaUnit>(AreaMomentOfInertiaUnit.CentimeterToTheFourth, "CentimetersToTheFourth", new BaseUnits(length: LengthUnit.Centimeter)), + new UnitInfo<AreaMomentOfInertiaUnit>(AreaMomentOfInertiaUnit.DecimeterToTheFourth, "DecimetersToTheFourth", new BaseUnits(length: LengthUnit.Decimeter)), + new UnitInfo<AreaMomentOfInertiaUnit>(AreaMomentOfInertiaUnit.FootToTheFourth, "FeetToTheFourth", new BaseUnits(length: LengthUnit.Foot)), + new UnitInfo<AreaMomentOfInertiaUnit>(AreaMomentOfInertiaUnit.InchToTheFourth, "InchesToTheFourth", new BaseUnits(length: LengthUnit.Inch)), + new UnitInfo<AreaMomentOfInertiaUnit>(AreaMomentOfInertiaUnit.MeterToTheFourth, "MetersToTheFourth", new BaseUnits(length: LengthUnit.Meter)), + new UnitInfo<AreaMomentOfInertiaUnit>(AreaMomentOfInertiaUnit.MillimeterToTheFourth, "MillimetersToTheFourth", new BaseUnits(length: LengthUnit.Millimeter)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public AreaMomentOfInertia(double value, AreaMomentOfInertiaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="AreaMomentOfInertia" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<AreaMomentOfInertiaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. + /// </summary> + public static AreaMomentOfInertiaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the AreaMomentOfInertia quantity. + /// </summary> + public static AreaMomentOfInertiaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. + /// </summary> + public static AreaMomentOfInertia Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static AreaMomentOfInertia AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<AreaMomentOfInertiaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaMomentOfInertiaUnit.CentimeterToTheFourth"/> + /// </summary> + public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaMomentOfInertiaUnit.DecimeterToTheFourth"/> + /// </summary> + public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaMomentOfInertiaUnit.FootToTheFourth"/> + /// </summary> + public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaMomentOfInertiaUnit.InchToTheFourth"/> + /// </summary> + public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaMomentOfInertiaUnit.MeterToTheFourth"/> + /// </summary> + public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="AreaMomentOfInertiaUnit.MillimeterToTheFourth"/> + /// </summary> + public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: AreaMomentOfInertiaUnit -> BaseUnit + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.CentimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.DecimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.FootToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.InchToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MillimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity); + + // Register in unit converter: BaseUnit -> AreaMomentOfInertiaUnit + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.CentimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.CentimeterToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.DecimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.DecimeterToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.FootToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.FootToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.InchToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.InchToTheFourth)); + unitConverter.SetConversionFunction<AreaMomentOfInertia>(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MillimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MillimeterToTheFourth)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(AreaMomentOfInertiaUnit.CentimeterToTheFourth, new CultureInfo("en-US"), false, true, new string[]{"cm⁴", "cm^4"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaMomentOfInertiaUnit.DecimeterToTheFourth, new CultureInfo("en-US"), false, true, new string[]{"dm⁴", "dm^4"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaMomentOfInertiaUnit.FootToTheFourth, new CultureInfo("en-US"), false, true, new string[]{"ft⁴", "ft^4"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaMomentOfInertiaUnit.InchToTheFourth, new CultureInfo("en-US"), false, true, new string[]{"in⁴", "in^4"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaMomentOfInertiaUnit.MeterToTheFourth, new CultureInfo("en-US"), false, true, new string[]{"m⁴", "m^4"}); + unitAbbreviationsCache.PerformAbbreviationMapping(AreaMomentOfInertiaUnit.MillimeterToTheFourth, new CultureInfo("en-US"), false, true, new string[]{"mm⁴", "mm^4"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="AreaMomentOfInertia"/> from <see cref="AreaMomentOfInertiaUnit.CentimeterToTheFourth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) + { + double value = (double) centimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); + } + + /// <summary> + /// Creates a <see cref="AreaMomentOfInertia"/> from <see cref="AreaMomentOfInertiaUnit.DecimeterToTheFourth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) + { + double value = (double) decimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); + } + + /// <summary> + /// Creates a <see cref="AreaMomentOfInertia"/> from <see cref="AreaMomentOfInertiaUnit.FootToTheFourth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) + { + double value = (double) feettothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); + } + + /// <summary> + /// Creates a <see cref="AreaMomentOfInertia"/> from <see cref="AreaMomentOfInertiaUnit.InchToTheFourth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) + { + double value = (double) inchestothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); + } + + /// <summary> + /// Creates a <see cref="AreaMomentOfInertia"/> from <see cref="AreaMomentOfInertiaUnit.MeterToTheFourth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) + { + double value = (double) meterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); + } + + /// <summary> + /// Creates a <see cref="AreaMomentOfInertia"/> from <see cref="AreaMomentOfInertiaUnit.MillimeterToTheFourth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) + { + double value = (double) millimeterstothefourth; + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="AreaMomentOfInertiaUnit" /> to <see cref="AreaMomentOfInertia" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>AreaMomentOfInertia unit value.</returns> + public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) + { + return new AreaMomentOfInertia((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static AreaMomentOfInertia Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static AreaMomentOfInertia Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<AreaMomentOfInertia, AreaMomentOfInertiaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out AreaMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out AreaMomentOfInertia result) + { + return QuantityParser.Default.TryParse<AreaMomentOfInertia, AreaMomentOfInertiaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AreaMomentOfInertiaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<AreaMomentOfInertiaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.AreaMomentOfInertiaUnit)"/> + public static bool TryParseUnit(string str, out AreaMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out AreaMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse<AreaMomentOfInertiaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static AreaMomentOfInertia operator -(AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="AreaMomentOfInertia"/> from adding two <see cref="AreaMomentOfInertia"/>.</summary> + public static AreaMomentOfInertia operator +(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="AreaMomentOfInertia"/> from subtracting two <see cref="AreaMomentOfInertia"/>.</summary> + public static AreaMomentOfInertia operator -(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="AreaMomentOfInertia"/> from multiplying value and <see cref="AreaMomentOfInertia"/>.</summary> + public static AreaMomentOfInertia operator *(double left, AreaMomentOfInertia right) + { + return new AreaMomentOfInertia(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="AreaMomentOfInertia"/> from multiplying value and <see cref="AreaMomentOfInertia"/>.</summary> + public static AreaMomentOfInertia operator *(AreaMomentOfInertia left, double right) + { + return new AreaMomentOfInertia(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="AreaMomentOfInertia"/> from dividing <see cref="AreaMomentOfInertia"/> by value.</summary> + public static AreaMomentOfInertia operator /(AreaMomentOfInertia left, double right) + { + return new AreaMomentOfInertia(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="AreaMomentOfInertia"/> by <see cref="AreaMomentOfInertia"/>.</summary> + public static double operator /(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.MetersToTheFourth / right.MetersToTheFourth; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="AreaMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="AreaMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AreaMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is AreaMomentOfInertia otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="AreaMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(AreaMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(AreaMomentOfInertia other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="AreaMomentOfInertia"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is AreaMomentOfInertia otherQuantity)) throw new ArgumentException("Expected type AreaMomentOfInertia.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="AreaMomentOfInertia"/> with another <see cref="AreaMomentOfInertia"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(AreaMomentOfInertia other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another AreaMomentOfInertia within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current AreaMomentOfInertia.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(AreaMomentOfInertiaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is AreaMomentOfInertiaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A AreaMomentOfInertia with the specified unit.</returns> + public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="AreaMomentOfInertia"/> to another <see cref="AreaMomentOfInertia"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A AreaMomentOfInertia with the specified unit.</returns> + public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(AreaMomentOfInertia), Unit, typeof(AreaMomentOfInertia), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (AreaMomentOfInertia)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="AreaMomentOfInertia"/> to another <see cref="AreaMomentOfInertia"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="AreaMomentOfInertia"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(AreaMomentOfInertiaUnit unit, [NotNullWhen(true)] out AreaMomentOfInertia? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + AreaMomentOfInertia? convertedOrNull = (Unit, unit) switch + { + // AreaMomentOfInertiaUnit -> BaseUnit + (AreaMomentOfInertiaUnit.CentimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value / 1e8, AreaMomentOfInertiaUnit.MeterToTheFourth), + (AreaMomentOfInertiaUnit.DecimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value / 1e4, AreaMomentOfInertiaUnit.MeterToTheFourth), + (AreaMomentOfInertiaUnit.FootToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value * Math.Pow(0.3048, 4), AreaMomentOfInertiaUnit.MeterToTheFourth), + (AreaMomentOfInertiaUnit.InchToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value * Math.Pow(2.54e-2, 4), AreaMomentOfInertiaUnit.MeterToTheFourth), + (AreaMomentOfInertiaUnit.MillimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value / 1e12, AreaMomentOfInertiaUnit.MeterToTheFourth), + + // BaseUnit -> AreaMomentOfInertiaUnit + (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.CentimeterToTheFourth) => new AreaMomentOfInertia(_value * 1e8, AreaMomentOfInertiaUnit.CentimeterToTheFourth), + (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.DecimeterToTheFourth) => new AreaMomentOfInertia(_value * 1e4, AreaMomentOfInertiaUnit.DecimeterToTheFourth), + (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.FootToTheFourth) => new AreaMomentOfInertia(_value / Math.Pow(0.3048, 4), AreaMomentOfInertiaUnit.FootToTheFourth), + (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.InchToTheFourth) => new AreaMomentOfInertia(_value / Math.Pow(2.54e-2, 4), AreaMomentOfInertiaUnit.InchToTheFourth), + (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MillimeterToTheFourth) => new AreaMomentOfInertia(_value * 1e12, AreaMomentOfInertiaUnit.MillimeterToTheFourth), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is AreaMomentOfInertiaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<AreaMomentOfInertiaUnit> IQuantity<AreaMomentOfInertiaUnit>.ToUnit(AreaMomentOfInertiaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<AreaMomentOfInertiaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(AreaMomentOfInertia)) + return this; + else if (conversionType == typeof(AreaMomentOfInertiaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return AreaMomentOfInertia.Info; + else if (conversionType == typeof(BaseDimensions)) + return AreaMomentOfInertia.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertiaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertiaUnit.g.cs new file mode 100644 index 0000000000..388a130b9d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/AreaMomentOfInertia/AreaMomentOfInertiaUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum AreaMomentOfInertiaUnit + { + CentimeterToTheFourth = 1, + DecimeterToTheFourth = 2, + FootToTheFourth = 3, + InchToTheFourth = 4, + MeterToTheFourth = 5, + MillimeterToTheFourth = 6, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/BitRate/BitRate.csproj b/UnitsNet.Modular/GeneratedCode/BitRate/BitRate.csproj new file mode 100644 index 0000000000..1714aa78e3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/BitRate/BitRate.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET BitRate</Title> + <Description>Adds BitRate units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>bitrate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{b5fdf997-829f-5281-e624-ee4eee5aa26c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.BitRate</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/BitRate/BitRate.g.cs b/UnitsNet.Modular/GeneratedCode/BitRate/BitRate.g.cs new file mode 100644 index 0000000000..ebd319db30 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/BitRate/BitRate.g.cs @@ -0,0 +1,1374 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Bit_rate + /// </remarks> + [DataContract] + public readonly partial struct BitRate : IArithmeticQuantity<BitRate, BitRateUnit, decimal>, IDecimalQuantity, IEquatable<BitRate>, IComparable, IComparable<BitRate>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly decimal _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly BitRateUnit? _unit; + + static BitRate() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + BaseUnit = BitRateUnit.BitPerSecond; + Units = Enum.GetValues(typeof(BitRateUnit)).Cast<BitRateUnit>().ToArray(); + Zero = new BitRate(0, BaseUnit); + Info = new QuantityInfo<BitRateUnit>("BitRate", + new UnitInfo<BitRateUnit>[] + { + new UnitInfo<BitRateUnit>(BitRateUnit.BitPerSecond, "BitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.BytePerSecond, "BytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.ExabitPerSecond, "ExabitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.ExabytePerSecond, "ExabytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.ExbibitPerSecond, "ExbibitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.ExbibytePerSecond, "ExbibytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.GibibitPerSecond, "GibibitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.GibibytePerSecond, "GibibytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.GigabitPerSecond, "GigabitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.GigabytePerSecond, "GigabytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.KibibitPerSecond, "KibibitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.KibibytePerSecond, "KibibytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.KilobitPerSecond, "KilobitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.KilobytePerSecond, "KilobytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.MebibitPerSecond, "MebibitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.MebibytePerSecond, "MebibytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.MegabitPerSecond, "MegabitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.MegabytePerSecond, "MegabytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.PebibitPerSecond, "PebibitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.PebibytePerSecond, "PebibytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.PetabitPerSecond, "PetabitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.PetabytePerSecond, "PetabytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.TebibitPerSecond, "TebibitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.TebibytePerSecond, "TebibytesPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.TerabitPerSecond, "TerabitsPerSecond", BaseUnits.Undefined), + new UnitInfo<BitRateUnit>(BitRateUnit.TerabytePerSecond, "TerabytesPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public BitRate(decimal value, BitRateUnit unit) + { + _value = value; + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="BitRate" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<BitRateUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. + /// </summary> + public static BitRateUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the BitRate quantity. + /// </summary> + public static BitRateUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. + /// </summary> + public static BitRate Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static BitRate AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public decimal Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + /// <inheritdoc cref="IDecimalQuantity.Value"/> + decimal IDecimalQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<BitRateUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => BitRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.BitPerSecond"/> + /// </summary> + public decimal BitsPerSecond => As(BitRateUnit.BitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.BytePerSecond"/> + /// </summary> + public decimal BytesPerSecond => As(BitRateUnit.BytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.ExabitPerSecond"/> + /// </summary> + public decimal ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.ExabytePerSecond"/> + /// </summary> + public decimal ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.ExbibitPerSecond"/> + /// </summary> + public decimal ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.ExbibytePerSecond"/> + /// </summary> + public decimal ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.GibibitPerSecond"/> + /// </summary> + public decimal GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.GibibytePerSecond"/> + /// </summary> + public decimal GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.GigabitPerSecond"/> + /// </summary> + public decimal GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.GigabytePerSecond"/> + /// </summary> + public decimal GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.KibibitPerSecond"/> + /// </summary> + public decimal KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.KibibytePerSecond"/> + /// </summary> + public decimal KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.KilobitPerSecond"/> + /// </summary> + public decimal KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.KilobytePerSecond"/> + /// </summary> + public decimal KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.MebibitPerSecond"/> + /// </summary> + public decimal MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.MebibytePerSecond"/> + /// </summary> + public decimal MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.MegabitPerSecond"/> + /// </summary> + public decimal MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.MegabytePerSecond"/> + /// </summary> + public decimal MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.PebibitPerSecond"/> + /// </summary> + public decimal PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.PebibytePerSecond"/> + /// </summary> + public decimal PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.PetabitPerSecond"/> + /// </summary> + public decimal PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.PetabytePerSecond"/> + /// </summary> + public decimal PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.TebibitPerSecond"/> + /// </summary> + public decimal TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.TebibytePerSecond"/> + /// </summary> + public decimal TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.TerabitPerSecond"/> + /// </summary> + public decimal TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="BitRateUnit.TerabytePerSecond"/> + /// </summary> + public decimal TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: BitRateUnit -> BaseUnit + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.ExabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.ExabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.ExbibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.ExbibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.GibibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.GibibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.GigabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.GigabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.KibibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.KibibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.KilobitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.KilobytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.MebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.MebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.MegabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.PebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.PebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.PetabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.PetabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.TebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.TebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.TerabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.TerabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> BitRateUnit + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.BytePerSecond, quantity => quantity.ToUnit(BitRateUnit.BytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.ExabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExabitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.ExabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExabytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.ExbibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibytePerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabitPerSecond)); + unitConverter.SetConversionFunction<BitRate>(BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabytePerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.BitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"bit/s", "bps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.BytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"B/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.ExabitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Ebit/s", "Ebps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.ExabytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"EB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.ExbibitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Eibit/s", "Eibps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.ExbibytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"EiB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.GibibitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Gibit/s", "Gibps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.GibibytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"GiB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.GigabitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Gbit/s", "Gbps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.GigabytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"GB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.KibibitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Kibit/s", "Kibps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.KibibytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"KiB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.KilobitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kbit/s", "kbps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.KilobytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"kB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.MebibitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Mibit/s", "Mibps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.MebibytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"MiB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.MegabitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Mbit/s", "Mbps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.MegabytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"MB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.PebibitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Pibit/s", "Pibps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.PebibytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"PiB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.PetabitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Pbit/s", "Pbps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.PetabytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"PB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.TebibitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Tibit/s", "Tibps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.TebibytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"TiB/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.TerabitPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Tbit/s", "Tbps"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BitRateUnit.TerabytePerSecond, new CultureInfo("en-US"), false, true, new string[]{"TB/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(BitRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(BitRateUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.BitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) + { + decimal value = (decimal) bitspersecond; + return new BitRate(value, BitRateUnit.BitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.BytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) + { + decimal value = (decimal) bytespersecond; + return new BitRate(value, BitRateUnit.BytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.ExabitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) + { + decimal value = (decimal) exabitspersecond; + return new BitRate(value, BitRateUnit.ExabitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.ExabytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) + { + decimal value = (decimal) exabytespersecond; + return new BitRate(value, BitRateUnit.ExabytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.ExbibitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) + { + decimal value = (decimal) exbibitspersecond; + return new BitRate(value, BitRateUnit.ExbibitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.ExbibytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) + { + decimal value = (decimal) exbibytespersecond; + return new BitRate(value, BitRateUnit.ExbibytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.GibibitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) + { + decimal value = (decimal) gibibitspersecond; + return new BitRate(value, BitRateUnit.GibibitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.GibibytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) + { + decimal value = (decimal) gibibytespersecond; + return new BitRate(value, BitRateUnit.GibibytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.GigabitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) + { + decimal value = (decimal) gigabitspersecond; + return new BitRate(value, BitRateUnit.GigabitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.GigabytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) + { + decimal value = (decimal) gigabytespersecond; + return new BitRate(value, BitRateUnit.GigabytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.KibibitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) + { + decimal value = (decimal) kibibitspersecond; + return new BitRate(value, BitRateUnit.KibibitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.KibibytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) + { + decimal value = (decimal) kibibytespersecond; + return new BitRate(value, BitRateUnit.KibibytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.KilobitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) + { + decimal value = (decimal) kilobitspersecond; + return new BitRate(value, BitRateUnit.KilobitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.KilobytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) + { + decimal value = (decimal) kilobytespersecond; + return new BitRate(value, BitRateUnit.KilobytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.MebibitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) + { + decimal value = (decimal) mebibitspersecond; + return new BitRate(value, BitRateUnit.MebibitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.MebibytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) + { + decimal value = (decimal) mebibytespersecond; + return new BitRate(value, BitRateUnit.MebibytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.MegabitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) + { + decimal value = (decimal) megabitspersecond; + return new BitRate(value, BitRateUnit.MegabitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.MegabytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) + { + decimal value = (decimal) megabytespersecond; + return new BitRate(value, BitRateUnit.MegabytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.PebibitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) + { + decimal value = (decimal) pebibitspersecond; + return new BitRate(value, BitRateUnit.PebibitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.PebibytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) + { + decimal value = (decimal) pebibytespersecond; + return new BitRate(value, BitRateUnit.PebibytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.PetabitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) + { + decimal value = (decimal) petabitspersecond; + return new BitRate(value, BitRateUnit.PetabitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.PetabytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) + { + decimal value = (decimal) petabytespersecond; + return new BitRate(value, BitRateUnit.PetabytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.TebibitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) + { + decimal value = (decimal) tebibitspersecond; + return new BitRate(value, BitRateUnit.TebibitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.TebibytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) + { + decimal value = (decimal) tebibytespersecond; + return new BitRate(value, BitRateUnit.TebibytePerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.TerabitPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) + { + decimal value = (decimal) terabitspersecond; + return new BitRate(value, BitRateUnit.TerabitPerSecond); + } + + /// <summary> + /// Creates a <see cref="BitRate"/> from <see cref="BitRateUnit.TerabytePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) + { + decimal value = (decimal) terabytespersecond; + return new BitRate(value, BitRateUnit.TerabytePerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="BitRateUnit" /> to <see cref="BitRate" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>BitRate unit value.</returns> + public static BitRate From(QuantityValue value, BitRateUnit fromUnit) + { + return new BitRate((decimal)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static BitRate Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static BitRate Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<BitRate, BitRateUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out BitRate result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out BitRate result) + { + return QuantityParser.Default.TryParse<BitRate, BitRateUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static BitRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static BitRateUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<BitRateUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.BitRateUnit)"/> + public static bool TryParseUnit(string str, out BitRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out BitRateUnit unit) + { + return UnitParser.Default.TryParse<BitRateUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static BitRate operator -(BitRate right) + { + return new BitRate(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="BitRate"/> from adding two <see cref="BitRate"/>.</summary> + public static BitRate operator +(BitRate left, BitRate right) + { + return new BitRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="BitRate"/> from subtracting two <see cref="BitRate"/>.</summary> + public static BitRate operator -(BitRate left, BitRate right) + { + return new BitRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="BitRate"/> from multiplying value and <see cref="BitRate"/>.</summary> + public static BitRate operator *(decimal left, BitRate right) + { + return new BitRate(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="BitRate"/> from multiplying value and <see cref="BitRate"/>.</summary> + public static BitRate operator *(BitRate left, decimal right) + { + return new BitRate(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="BitRate"/> from dividing <see cref="BitRate"/> by value.</summary> + public static BitRate operator /(BitRate left, decimal right) + { + return new BitRate(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="BitRate"/> by <see cref="BitRate"/>.</summary> + public static decimal operator /(BitRate left, BitRate right) + { + return left.BitsPerSecond / right.BitsPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(BitRate left, BitRate right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(BitRate left, BitRate right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(BitRate left, BitRate right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(BitRate left, BitRate right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="BitRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BitRate, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(BitRate left, BitRate right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="BitRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BitRate, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(BitRate left, BitRate right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="BitRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BitRate, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is BitRate otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="BitRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BitRate, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(BitRate other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="BitRate"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is BitRate otherQuantity)) throw new ArgumentException("Expected type BitRate.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="BitRate"/> with another <see cref="BitRate"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(BitRate other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another BitRate within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using decimal internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(BitRate other, decimal tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + decimal thisValue = this.Value; + decimal otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current BitRate.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public decimal As(BitRateUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + double IQuantity<BitRateUnit>.As(BitRateUnit unit) + { + return (double)As(unit); + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is BitRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this BitRate to another BitRate with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A BitRate with the specified unit.</returns> + public BitRate ToUnit(BitRateUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="BitRate"/> to another <see cref="BitRate"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A BitRate with the specified unit.</returns> + public BitRate ToUnit(BitRateUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(BitRate), Unit, typeof(BitRate), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (BitRate)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="BitRate"/> to another <see cref="BitRate"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="BitRate"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(BitRateUnit unit, [NotNullWhen(true)] out BitRate? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + BitRate? convertedOrNull = (Unit, unit) switch + { + // BitRateUnit -> BaseUnit + (BitRateUnit.BytePerSecond, BitRateUnit.BitPerSecond) => new BitRate(_value * 8m, BitRateUnit.BitPerSecond), + (BitRateUnit.ExabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e18m, BitRateUnit.BitPerSecond), + (BitRateUnit.ExabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1e18m, BitRateUnit.BitPerSecond), + (BitRateUnit.ExbibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.ExbibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.GibibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024m * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.GibibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * (1024m * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.GigabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e9m, BitRateUnit.BitPerSecond), + (BitRateUnit.GigabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1e9m, BitRateUnit.BitPerSecond), + (BitRateUnit.KibibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1024m, BitRateUnit.BitPerSecond), + (BitRateUnit.KibibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1024m, BitRateUnit.BitPerSecond), + (BitRateUnit.KilobitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e3m, BitRateUnit.BitPerSecond), + (BitRateUnit.KilobytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1e3m, BitRateUnit.BitPerSecond), + (BitRateUnit.MebibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024m * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.MebibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * (1024m * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.MegabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e6m, BitRateUnit.BitPerSecond), + (BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1e6m, BitRateUnit.BitPerSecond), + (BitRateUnit.PebibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.PebibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.PetabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e15m, BitRateUnit.BitPerSecond), + (BitRateUnit.PetabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1e15m, BitRateUnit.BitPerSecond), + (BitRateUnit.TebibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024m * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.TebibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * (1024m * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), + (BitRateUnit.TerabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e12m, BitRateUnit.BitPerSecond), + (BitRateUnit.TerabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8m) * 1e12m, BitRateUnit.BitPerSecond), + + // BaseUnit -> BitRateUnit + (BitRateUnit.BitPerSecond, BitRateUnit.BytePerSecond) => new BitRate(_value / 8m, BitRateUnit.BytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.ExabitPerSecond) => new BitRate((_value) / 1e18m, BitRateUnit.ExabitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.ExabytePerSecond) => new BitRate((_value / 8m) / 1e18m, BitRateUnit.ExabytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.ExbibitPerSecond) => new BitRate((_value) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbibitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond) => new BitRate((_value / 8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbibytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond) => new BitRate((_value) / (1024m * 1024 * 1024), BitRateUnit.GibibitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond) => new BitRate((_value / 8m) / (1024m * 1024 * 1024), BitRateUnit.GibibytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond) => new BitRate((_value) / 1e9m, BitRateUnit.GigabitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond) => new BitRate((_value / 8m) / 1e9m, BitRateUnit.GigabytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond) => new BitRate((_value) / 1024m, BitRateUnit.KibibitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond) => new BitRate((_value / 8m) / 1024m, BitRateUnit.KibibytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond) => new BitRate((_value) / 1e3m, BitRateUnit.KilobitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond) => new BitRate((_value / 8m) / 1e3m, BitRateUnit.KilobytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond) => new BitRate((_value) / (1024m * 1024), BitRateUnit.MebibitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond) => new BitRate((_value / 8m) / (1024m * 1024), BitRateUnit.MebibytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond) => new BitRate((_value) / 1e6m, BitRateUnit.MegabitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond) => new BitRate((_value / 8m) / 1e6m, BitRateUnit.MegabytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond) => new BitRate((_value) / (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebibitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond) => new BitRate((_value / 8m) / (1024m * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebibytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond) => new BitRate((_value) / 1e15m, BitRateUnit.PetabitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond) => new BitRate((_value / 8m) / 1e15m, BitRateUnit.PetabytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond) => new BitRate((_value) / (1024m * 1024 * 1024 * 1024), BitRateUnit.TebibitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond) => new BitRate((_value / 8m) / (1024m * 1024 * 1024 * 1024), BitRateUnit.TebibytePerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond) => new BitRate((_value) / 1e12m, BitRateUnit.TerabitPerSecond), + (BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond) => new BitRate((_value / 8m) / 1e12m, BitRateUnit.TerabytePerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is BitRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<BitRateUnit> IQuantity<BitRateUnit>.ToUnit(BitRateUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<BitRateUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(BitRate)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(BitRate)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(BitRate)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(BitRate)) + return this; + else if (conversionType == typeof(BitRateUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return BitRate.Info; + else if (conversionType == typeof(BaseDimensions)) + return BitRate.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(BitRate)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/BitRate/BitRateUnit.g.cs b/UnitsNet.Modular/GeneratedCode/BitRate/BitRateUnit.g.cs new file mode 100644 index 0000000000..6a3760ef6b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/BitRate/BitRateUnit.g.cs @@ -0,0 +1,57 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum BitRateUnit + { + BitPerSecond = 1, + BytePerSecond = 2, + ExabitPerSecond = 3, + ExabytePerSecond = 4, + ExbibitPerSecond = 5, + ExbibytePerSecond = 6, + GibibitPerSecond = 7, + GibibytePerSecond = 8, + GigabitPerSecond = 9, + GigabytePerSecond = 10, + KibibitPerSecond = 11, + KibibytePerSecond = 12, + KilobitPerSecond = 13, + KilobytePerSecond = 14, + MebibitPerSecond = 15, + MebibytePerSecond = 16, + MegabitPerSecond = 17, + MegabytePerSecond = 18, + PebibitPerSecond = 19, + PebibytePerSecond = 20, + PetabitPerSecond = 21, + PetabytePerSecond = 22, + TebibitPerSecond = 23, + TebibytePerSecond = 24, + TerabitPerSecond = 25, + TerabytePerSecond = 26, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumption.csproj b/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumption.csproj new file mode 100644 index 0000000000..c49f3af6f6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumption.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET BrakeSpecificFuelConsumption</Title> + <Description>Adds BrakeSpecificFuelConsumption units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>brakespecificfuelconsumption unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{085145f2-2b8f-4d09-5290-c14cdcd452bf}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.BrakeSpecificFuelConsumption</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumption.g.cs b/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumption.g.cs new file mode 100644 index 0000000000..0dcb5a49f0 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumption.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct BrakeSpecificFuelConsumption : IArithmeticQuantity<BrakeSpecificFuelConsumption, BrakeSpecificFuelConsumptionUnit, double>, IEquatable<BrakeSpecificFuelConsumption>, IComparable, IComparable<BrakeSpecificFuelConsumption>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly BrakeSpecificFuelConsumptionUnit? _unit; + + static BrakeSpecificFuelConsumption() + { + BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); + BaseUnit = BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; + Units = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast<BrakeSpecificFuelConsumptionUnit>().ToArray(); + Zero = new BrakeSpecificFuelConsumption(0, BaseUnit); + Info = new QuantityInfo<BrakeSpecificFuelConsumptionUnit>("BrakeSpecificFuelConsumption", + new UnitInfo<BrakeSpecificFuelConsumptionUnit>[] + { + new UnitInfo<BrakeSpecificFuelConsumptionUnit>(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, "GramsPerKiloWattHour", BaseUnits.Undefined), + new UnitInfo<BrakeSpecificFuelConsumptionUnit>(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, "KilogramsPerJoule", BaseUnits.Undefined), + new UnitInfo<BrakeSpecificFuelConsumptionUnit>(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "PoundsPerMechanicalHorsepowerHour", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public BrakeSpecificFuelConsumption(double value, BrakeSpecificFuelConsumptionUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="BrakeSpecificFuelConsumption" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<BrakeSpecificFuelConsumptionUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. + /// </summary> + public static BrakeSpecificFuelConsumptionUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the BrakeSpecificFuelConsumption quantity. + /// </summary> + public static BrakeSpecificFuelConsumptionUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. + /// </summary> + public static BrakeSpecificFuelConsumption Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static BrakeSpecificFuelConsumption AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<BrakeSpecificFuelConsumptionUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour"/> + /// </summary> + public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="BrakeSpecificFuelConsumptionUnit.KilogramPerJoule"/> + /// </summary> + public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour"/> + /// </summary> + public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: BrakeSpecificFuelConsumptionUnit -> BaseUnit + unitConverter.SetConversionFunction<BrakeSpecificFuelConsumption>(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule)); + unitConverter.SetConversionFunction<BrakeSpecificFuelConsumption>(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<BrakeSpecificFuelConsumption>(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity); + + // Register in unit converter: BaseUnit -> BrakeSpecificFuelConsumptionUnit + unitConverter.SetConversionFunction<BrakeSpecificFuelConsumption>(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour)); + unitConverter.SetConversionFunction<BrakeSpecificFuelConsumption>(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, new CultureInfo("en-US"), false, true, new string[]{"g/kWh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, new CultureInfo("en-US"), false, true, new string[]{"kg/J"}); + unitAbbreviationsCache.PerformAbbreviationMapping(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, new CultureInfo("en-US"), false, true, new string[]{"lb/hph"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="BrakeSpecificFuelConsumption"/> from <see cref="BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) + { + double value = (double) gramsperkilowatthour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + } + + /// <summary> + /// Creates a <see cref="BrakeSpecificFuelConsumption"/> from <see cref="BrakeSpecificFuelConsumptionUnit.KilogramPerJoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) + { + double value = (double) kilogramsperjoule; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + } + + /// <summary> + /// Creates a <see cref="BrakeSpecificFuelConsumption"/> from <see cref="BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) + { + double value = (double) poundspermechanicalhorsepowerhour; + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="BrakeSpecificFuelConsumptionUnit" /> to <see cref="BrakeSpecificFuelConsumption" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>BrakeSpecificFuelConsumption unit value.</returns> + public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) + { + return new BrakeSpecificFuelConsumption((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static BrakeSpecificFuelConsumption Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static BrakeSpecificFuelConsumption Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<BrakeSpecificFuelConsumption, BrakeSpecificFuelConsumptionUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out BrakeSpecificFuelConsumption result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out BrakeSpecificFuelConsumption result) + { + return QuantityParser.Default.TryParse<BrakeSpecificFuelConsumption, BrakeSpecificFuelConsumptionUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<BrakeSpecificFuelConsumptionUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.BrakeSpecificFuelConsumptionUnit)"/> + public static bool TryParseUnit(string str, out BrakeSpecificFuelConsumptionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out BrakeSpecificFuelConsumptionUnit unit) + { + return UnitParser.Default.TryParse<BrakeSpecificFuelConsumptionUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="BrakeSpecificFuelConsumption"/> from adding two <see cref="BrakeSpecificFuelConsumption"/>.</summary> + public static BrakeSpecificFuelConsumption operator +(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="BrakeSpecificFuelConsumption"/> from subtracting two <see cref="BrakeSpecificFuelConsumption"/>.</summary> + public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="BrakeSpecificFuelConsumption"/> from multiplying value and <see cref="BrakeSpecificFuelConsumption"/>.</summary> + public static BrakeSpecificFuelConsumption operator *(double left, BrakeSpecificFuelConsumption right) + { + return new BrakeSpecificFuelConsumption(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="BrakeSpecificFuelConsumption"/> from multiplying value and <see cref="BrakeSpecificFuelConsumption"/>.</summary> + public static BrakeSpecificFuelConsumption operator *(BrakeSpecificFuelConsumption left, double right) + { + return new BrakeSpecificFuelConsumption(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="BrakeSpecificFuelConsumption"/> from dividing <see cref="BrakeSpecificFuelConsumption"/> by value.</summary> + public static BrakeSpecificFuelConsumption operator /(BrakeSpecificFuelConsumption left, double right) + { + return new BrakeSpecificFuelConsumption(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="BrakeSpecificFuelConsumption"/> by <see cref="BrakeSpecificFuelConsumption"/>.</summary> + public static double operator /(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.KilogramsPerJoule / right.KilogramsPerJoule; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="BrakeSpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BrakeSpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="BrakeSpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BrakeSpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="BrakeSpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BrakeSpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is BrakeSpecificFuelConsumption otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="BrakeSpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(BrakeSpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(BrakeSpecificFuelConsumption other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="BrakeSpecificFuelConsumption"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is BrakeSpecificFuelConsumption otherQuantity)) throw new ArgumentException("Expected type BrakeSpecificFuelConsumption.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="BrakeSpecificFuelConsumption"/> with another <see cref="BrakeSpecificFuelConsumption"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(BrakeSpecificFuelConsumption other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another BrakeSpecificFuelConsumption within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current BrakeSpecificFuelConsumption.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(BrakeSpecificFuelConsumptionUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is BrakeSpecificFuelConsumptionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A BrakeSpecificFuelConsumption with the specified unit.</returns> + public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="BrakeSpecificFuelConsumption"/> to another <see cref="BrakeSpecificFuelConsumption"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A BrakeSpecificFuelConsumption with the specified unit.</returns> + public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(BrakeSpecificFuelConsumption), Unit, typeof(BrakeSpecificFuelConsumption), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (BrakeSpecificFuelConsumption)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="BrakeSpecificFuelConsumption"/> to another <see cref="BrakeSpecificFuelConsumption"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="BrakeSpecificFuelConsumption"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(BrakeSpecificFuelConsumptionUnit unit, [NotNullWhen(true)] out BrakeSpecificFuelConsumption? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + BrakeSpecificFuelConsumption? convertedOrNull = (Unit, unit) switch + { + // BrakeSpecificFuelConsumptionUnit -> BaseUnit + (BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule) => new BrakeSpecificFuelConsumption(_value / 3.6e9, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule), + (BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule) => new BrakeSpecificFuelConsumption(_value * 1.689659410672e-7, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule), + + // BaseUnit -> BrakeSpecificFuelConsumptionUnit + (BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour) => new BrakeSpecificFuelConsumption(_value * 3.6e9, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour), + (BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour) => new BrakeSpecificFuelConsumption(_value / 1.689659410672e-7, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is BrakeSpecificFuelConsumptionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<BrakeSpecificFuelConsumptionUnit> IQuantity<BrakeSpecificFuelConsumptionUnit>.ToUnit(BrakeSpecificFuelConsumptionUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<BrakeSpecificFuelConsumptionUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(BrakeSpecificFuelConsumption)) + return this; + else if (conversionType == typeof(BrakeSpecificFuelConsumptionUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return BrakeSpecificFuelConsumption.Info; + else if (conversionType == typeof(BaseDimensions)) + return BrakeSpecificFuelConsumption.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumptionUnit.g.cs b/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumptionUnit.g.cs new file mode 100644 index 0000000000..73c93e2039 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/BrakeSpecificFuelConsumption/BrakeSpecificFuelConsumptionUnit.g.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum BrakeSpecificFuelConsumptionUnit + { + GramPerKiloWattHour = 1, + KilogramPerJoule = 2, + + /// <summary> + /// The pound per horse power hour uses mechanical horse power and the imperial pound + /// </summary> + PoundPerMechanicalHorsepowerHour = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Capacitance/Capacitance.csproj b/UnitsNet.Modular/GeneratedCode/Capacitance/Capacitance.csproj new file mode 100644 index 0000000000..0fc5c06604 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Capacitance/Capacitance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Capacitance</Title> + <Description>Adds Capacitance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>capacitance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c1351fc7-d3d8-c3ce-0715-ad8e18ab8c94}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Capacitance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Capacitance/Capacitance.g.cs b/UnitsNet.Modular/GeneratedCode/Capacitance/Capacitance.g.cs new file mode 100644 index 0000000000..db34d97525 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Capacitance/Capacitance.g.cs @@ -0,0 +1,967 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Capacitance is the ability of a body to store an electric charge. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Capacitance + /// </remarks> + [DataContract] + public readonly partial struct Capacitance : IArithmeticQuantity<Capacitance, CapacitanceUnit, double>, IEquatable<Capacitance>, IComparable, IComparable<Capacitance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly CapacitanceUnit? _unit; + + static Capacitance() + { + BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); + BaseUnit = CapacitanceUnit.Farad; + Units = Enum.GetValues(typeof(CapacitanceUnit)).Cast<CapacitanceUnit>().ToArray(); + Zero = new Capacitance(0, BaseUnit); + Info = new QuantityInfo<CapacitanceUnit>("Capacitance", + new UnitInfo<CapacitanceUnit>[] + { + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Farad, "Farads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Kilofarad, "Kilofarads", BaseUnits.Undefined), + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Megafarad, "Megafarads", BaseUnits.Undefined), + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Microfarad, "Microfarads", BaseUnits.Undefined), + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Millifarad, "Millifarads", BaseUnits.Undefined), + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Nanofarad, "Nanofarads", BaseUnits.Undefined), + new UnitInfo<CapacitanceUnit>(CapacitanceUnit.Picofarad, "Picofarads", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Capacitance(double value, CapacitanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Capacitance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<CapacitanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Capacitance, which is Farad. All conversions go via this value. + /// </summary> + public static CapacitanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Capacitance quantity. + /// </summary> + public static CapacitanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Farad. + /// </summary> + public static Capacitance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Capacitance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<CapacitanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Capacitance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Farad"/> + /// </summary> + public double Farads => As(CapacitanceUnit.Farad); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Kilofarad"/> + /// </summary> + public double Kilofarads => As(CapacitanceUnit.Kilofarad); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Megafarad"/> + /// </summary> + public double Megafarads => As(CapacitanceUnit.Megafarad); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Microfarad"/> + /// </summary> + public double Microfarads => As(CapacitanceUnit.Microfarad); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Millifarad"/> + /// </summary> + public double Millifarads => As(CapacitanceUnit.Millifarad); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Nanofarad"/> + /// </summary> + public double Nanofarads => As(CapacitanceUnit.Nanofarad); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CapacitanceUnit.Picofarad"/> + /// </summary> + public double Picofarads => As(CapacitanceUnit.Picofarad); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: CapacitanceUnit -> BaseUnit + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Kilofarad, CapacitanceUnit.Farad, quantity => quantity.ToUnit(CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Megafarad, CapacitanceUnit.Farad, quantity => quantity.ToUnit(CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Microfarad, CapacitanceUnit.Farad, quantity => quantity.ToUnit(CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Millifarad, CapacitanceUnit.Farad, quantity => quantity.ToUnit(CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Nanofarad, CapacitanceUnit.Farad, quantity => quantity.ToUnit(CapacitanceUnit.Farad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Picofarad, CapacitanceUnit.Farad, quantity => quantity.ToUnit(CapacitanceUnit.Farad)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Farad, quantity => quantity); + + // Register in unit converter: BaseUnit -> CapacitanceUnit + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Kilofarad, quantity => quantity.ToUnit(CapacitanceUnit.Kilofarad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Megafarad, quantity => quantity.ToUnit(CapacitanceUnit.Megafarad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Microfarad, quantity => quantity.ToUnit(CapacitanceUnit.Microfarad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Millifarad, quantity => quantity.ToUnit(CapacitanceUnit.Millifarad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Nanofarad, quantity => quantity.ToUnit(CapacitanceUnit.Nanofarad)); + unitConverter.SetConversionFunction<Capacitance>(CapacitanceUnit.Farad, CapacitanceUnit.Picofarad, quantity => quantity.ToUnit(CapacitanceUnit.Picofarad)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Farad, new CultureInfo("en-US"), false, true, new string[]{"F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Kilofarad, new CultureInfo("en-US"), false, true, new string[]{"kF"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Megafarad, new CultureInfo("en-US"), false, true, new string[]{"MF"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Microfarad, new CultureInfo("en-US"), false, true, new string[]{"µF"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Millifarad, new CultureInfo("en-US"), false, true, new string[]{"mF"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Nanofarad, new CultureInfo("en-US"), false, true, new string[]{"nF"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CapacitanceUnit.Picofarad, new CultureInfo("en-US"), false, true, new string[]{"pF"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(CapacitanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(CapacitanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Farad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromFarads(QuantityValue farads) + { + double value = (double) farads; + return new Capacitance(value, CapacitanceUnit.Farad); + } + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Kilofarad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromKilofarads(QuantityValue kilofarads) + { + double value = (double) kilofarads; + return new Capacitance(value, CapacitanceUnit.Kilofarad); + } + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Megafarad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromMegafarads(QuantityValue megafarads) + { + double value = (double) megafarads; + return new Capacitance(value, CapacitanceUnit.Megafarad); + } + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Microfarad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromMicrofarads(QuantityValue microfarads) + { + double value = (double) microfarads; + return new Capacitance(value, CapacitanceUnit.Microfarad); + } + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Millifarad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromMillifarads(QuantityValue millifarads) + { + double value = (double) millifarads; + return new Capacitance(value, CapacitanceUnit.Millifarad); + } + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Nanofarad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromNanofarads(QuantityValue nanofarads) + { + double value = (double) nanofarads; + return new Capacitance(value, CapacitanceUnit.Nanofarad); + } + + /// <summary> + /// Creates a <see cref="Capacitance"/> from <see cref="CapacitanceUnit.Picofarad"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Capacitance FromPicofarads(QuantityValue picofarads) + { + double value = (double) picofarads; + return new Capacitance(value, CapacitanceUnit.Picofarad); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="CapacitanceUnit" /> to <see cref="Capacitance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Capacitance unit value.</returns> + public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) + { + return new Capacitance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Capacitance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Capacitance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Capacitance, CapacitanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Capacitance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Capacitance result) + { + return QuantityParser.Default.TryParse<Capacitance, CapacitanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static CapacitanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static CapacitanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<CapacitanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.CapacitanceUnit)"/> + public static bool TryParseUnit(string str, out CapacitanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out CapacitanceUnit unit) + { + return UnitParser.Default.TryParse<CapacitanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Capacitance operator -(Capacitance right) + { + return new Capacitance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Capacitance"/> from adding two <see cref="Capacitance"/>.</summary> + public static Capacitance operator +(Capacitance left, Capacitance right) + { + return new Capacitance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Capacitance"/> from subtracting two <see cref="Capacitance"/>.</summary> + public static Capacitance operator -(Capacitance left, Capacitance right) + { + return new Capacitance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Capacitance"/> from multiplying value and <see cref="Capacitance"/>.</summary> + public static Capacitance operator *(double left, Capacitance right) + { + return new Capacitance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Capacitance"/> from multiplying value and <see cref="Capacitance"/>.</summary> + public static Capacitance operator *(Capacitance left, double right) + { + return new Capacitance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Capacitance"/> from dividing <see cref="Capacitance"/> by value.</summary> + public static Capacitance operator /(Capacitance left, double right) + { + return new Capacitance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Capacitance"/> by <see cref="Capacitance"/>.</summary> + public static double operator /(Capacitance left, Capacitance right) + { + return left.Farads / right.Farads; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Capacitance left, Capacitance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Capacitance left, Capacitance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Capacitance left, Capacitance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Capacitance left, Capacitance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Capacitance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Capacitance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Capacitance left, Capacitance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Capacitance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Capacitance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Capacitance left, Capacitance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Capacitance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Capacitance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Capacitance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Capacitance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Capacitance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Capacitance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Capacitance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Capacitance otherQuantity)) throw new ArgumentException("Expected type Capacitance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Capacitance"/> with another <see cref="Capacitance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Capacitance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Capacitance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Capacitance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(CapacitanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is CapacitanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Capacitance to another Capacitance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Capacitance with the specified unit.</returns> + public Capacitance ToUnit(CapacitanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Capacitance"/> to another <see cref="Capacitance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Capacitance with the specified unit.</returns> + public Capacitance ToUnit(CapacitanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Capacitance), Unit, typeof(Capacitance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Capacitance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Capacitance"/> to another <see cref="Capacitance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Capacitance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(CapacitanceUnit unit, [NotNullWhen(true)] out Capacitance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Capacitance? convertedOrNull = (Unit, unit) switch + { + // CapacitanceUnit -> BaseUnit + (CapacitanceUnit.Kilofarad, CapacitanceUnit.Farad) => new Capacitance((_value) * 1e3d, CapacitanceUnit.Farad), + (CapacitanceUnit.Megafarad, CapacitanceUnit.Farad) => new Capacitance((_value) * 1e6d, CapacitanceUnit.Farad), + (CapacitanceUnit.Microfarad, CapacitanceUnit.Farad) => new Capacitance((_value) * 1e-6d, CapacitanceUnit.Farad), + (CapacitanceUnit.Millifarad, CapacitanceUnit.Farad) => new Capacitance((_value) * 1e-3d, CapacitanceUnit.Farad), + (CapacitanceUnit.Nanofarad, CapacitanceUnit.Farad) => new Capacitance((_value) * 1e-9d, CapacitanceUnit.Farad), + (CapacitanceUnit.Picofarad, CapacitanceUnit.Farad) => new Capacitance((_value) * 1e-12d, CapacitanceUnit.Farad), + + // BaseUnit -> CapacitanceUnit + (CapacitanceUnit.Farad, CapacitanceUnit.Kilofarad) => new Capacitance((_value) / 1e3d, CapacitanceUnit.Kilofarad), + (CapacitanceUnit.Farad, CapacitanceUnit.Megafarad) => new Capacitance((_value) / 1e6d, CapacitanceUnit.Megafarad), + (CapacitanceUnit.Farad, CapacitanceUnit.Microfarad) => new Capacitance((_value) / 1e-6d, CapacitanceUnit.Microfarad), + (CapacitanceUnit.Farad, CapacitanceUnit.Millifarad) => new Capacitance((_value) / 1e-3d, CapacitanceUnit.Millifarad), + (CapacitanceUnit.Farad, CapacitanceUnit.Nanofarad) => new Capacitance((_value) / 1e-9d, CapacitanceUnit.Nanofarad), + (CapacitanceUnit.Farad, CapacitanceUnit.Picofarad) => new Capacitance((_value) / 1e-12d, CapacitanceUnit.Picofarad), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is CapacitanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CapacitanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<CapacitanceUnit> IQuantity<CapacitanceUnit>.ToUnit(CapacitanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<CapacitanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Capacitance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Capacitance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Capacitance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Capacitance)) + return this; + else if (conversionType == typeof(CapacitanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Capacitance.Info; + else if (conversionType == typeof(BaseDimensions)) + return Capacitance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Capacitance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Capacitance/CapacitanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Capacitance/CapacitanceUnit.g.cs new file mode 100644 index 0000000000..a76cc8f2d8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Capacitance/CapacitanceUnit.g.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum CapacitanceUnit + { + Farad = 1, + Kilofarad = 2, + Megafarad = 3, + Microfarad = 4, + Millifarad = 5, + Nanofarad = 6, + Picofarad = 7, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansion.csproj b/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansion.csproj new file mode 100644 index 0000000000..29b3d3f599 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansion.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET CoefficientOfThermalExpansion</Title> + <Description>Adds CoefficientOfThermalExpansion units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>coefficientofthermalexpansion unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{a9514ce6-d4e7-88ca-051e-e9e53610c519}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.CoefficientOfThermalExpansion</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansion.g.cs b/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansion.g.cs new file mode 100644 index 0000000000..98539d3ad5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansion.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// A unit that represents a fractional change in size in response to a change in temperature. + /// </summary> + [DataContract] + public readonly partial struct CoefficientOfThermalExpansion : IArithmeticQuantity<CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit, double>, IEquatable<CoefficientOfThermalExpansion>, IComparable, IComparable<CoefficientOfThermalExpansion>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly CoefficientOfThermalExpansionUnit? _unit; + + static CoefficientOfThermalExpansion() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); + BaseUnit = CoefficientOfThermalExpansionUnit.InverseKelvin; + Units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast<CoefficientOfThermalExpansionUnit>().ToArray(); + Zero = new CoefficientOfThermalExpansion(0, BaseUnit); + Info = new QuantityInfo<CoefficientOfThermalExpansionUnit>("CoefficientOfThermalExpansion", + new UnitInfo<CoefficientOfThermalExpansionUnit>[] + { + new UnitInfo<CoefficientOfThermalExpansionUnit>(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, "InverseDegreeCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)), + new UnitInfo<CoefficientOfThermalExpansionUnit>(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, "InverseDegreeFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)), + new UnitInfo<CoefficientOfThermalExpansionUnit>(CoefficientOfThermalExpansionUnit.InverseKelvin, "InverseKelvin", new BaseUnits(temperature: TemperatureUnit.Kelvin)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansionUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="CoefficientOfThermalExpansion" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<CoefficientOfThermalExpansionUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of CoefficientOfThermalExpansion, which is InverseKelvin. All conversions go via this value. + /// </summary> + public static CoefficientOfThermalExpansionUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the CoefficientOfThermalExpansion quantity. + /// </summary> + public static CoefficientOfThermalExpansionUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit InverseKelvin. + /// </summary> + public static CoefficientOfThermalExpansion Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static CoefficientOfThermalExpansion AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<CoefficientOfThermalExpansionUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeCelsius"/> + /// </summary> + public double InverseDegreeCelsius => As(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit"/> + /// </summary> + public double InverseDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CoefficientOfThermalExpansionUnit.InverseKelvin"/> + /// </summary> + public double InverseKelvin => As(CoefficientOfThermalExpansionUnit.InverseKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: CoefficientOfThermalExpansionUnit -> BaseUnit + unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.InverseKelvin)); + unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.InverseKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> CoefficientOfThermalExpansionUnit + unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius)); + unitConverter.SetConversionFunction<CoefficientOfThermalExpansion>(CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"°C⁻¹", "1/°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"°F⁻¹", "1/°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CoefficientOfThermalExpansionUnit.InverseKelvin, new CultureInfo("en-US"), false, true, new string[]{"K⁻¹", "1/K"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="CoefficientOfThermalExpansion"/> from <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static CoefficientOfThermalExpansion FromInverseDegreeCelsius(QuantityValue inversedegreecelsius) + { + double value = (double) inversedegreecelsius; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="CoefficientOfThermalExpansion"/> from <see cref="CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static CoefficientOfThermalExpansion FromInverseDegreeFahrenheit(QuantityValue inversedegreefahrenheit) + { + double value = (double) inversedegreefahrenheit; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit); + } + + /// <summary> + /// Creates a <see cref="CoefficientOfThermalExpansion"/> from <see cref="CoefficientOfThermalExpansionUnit.InverseKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static CoefficientOfThermalExpansion FromInverseKelvin(QuantityValue inversekelvin) + { + double value = (double) inversekelvin; + return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.InverseKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="CoefficientOfThermalExpansionUnit" /> to <see cref="CoefficientOfThermalExpansion" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>CoefficientOfThermalExpansion unit value.</returns> + public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit) + { + return new CoefficientOfThermalExpansion((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static CoefficientOfThermalExpansion Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static CoefficientOfThermalExpansion Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out CoefficientOfThermalExpansion result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out CoefficientOfThermalExpansion result) + { + return QuantityParser.Default.TryParse<CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static CoefficientOfThermalExpansionUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<CoefficientOfThermalExpansionUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.CoefficientOfThermalExpansionUnit)"/> + public static bool TryParseUnit(string str, out CoefficientOfThermalExpansionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out CoefficientOfThermalExpansionUnit unit) + { + return UnitParser.Default.TryParse<CoefficientOfThermalExpansionUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from adding two <see cref="CoefficientOfThermalExpansion"/>.</summary> + public static CoefficientOfThermalExpansion operator +(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from subtracting two <see cref="CoefficientOfThermalExpansion"/>.</summary> + public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from multiplying value and <see cref="CoefficientOfThermalExpansion"/>.</summary> + public static CoefficientOfThermalExpansion operator *(double left, CoefficientOfThermalExpansion right) + { + return new CoefficientOfThermalExpansion(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from multiplying value and <see cref="CoefficientOfThermalExpansion"/>.</summary> + public static CoefficientOfThermalExpansion operator *(CoefficientOfThermalExpansion left, double right) + { + return new CoefficientOfThermalExpansion(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="CoefficientOfThermalExpansion"/> from dividing <see cref="CoefficientOfThermalExpansion"/> by value.</summary> + public static CoefficientOfThermalExpansion operator /(CoefficientOfThermalExpansion left, double right) + { + return new CoefficientOfThermalExpansion(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="CoefficientOfThermalExpansion"/> by <see cref="CoefficientOfThermalExpansion"/>.</summary> + public static double operator /(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.InverseKelvin / right.InverseKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="CoefficientOfThermalExpansion"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="CoefficientOfThermalExpansion"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="CoefficientOfThermalExpansion"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is CoefficientOfThermalExpansion otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="CoefficientOfThermalExpansion"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(CoefficientOfThermalExpansion, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(CoefficientOfThermalExpansion other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="CoefficientOfThermalExpansion"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is CoefficientOfThermalExpansion otherQuantity)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="CoefficientOfThermalExpansion"/> with another <see cref="CoefficientOfThermalExpansion"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(CoefficientOfThermalExpansion other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another CoefficientOfThermalExpansion within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current CoefficientOfThermalExpansion.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(CoefficientOfThermalExpansionUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is CoefficientOfThermalExpansionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A CoefficientOfThermalExpansion with the specified unit.</returns> + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="CoefficientOfThermalExpansion"/> to another <see cref="CoefficientOfThermalExpansion"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A CoefficientOfThermalExpansion with the specified unit.</returns> + public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(CoefficientOfThermalExpansion), Unit, typeof(CoefficientOfThermalExpansion), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (CoefficientOfThermalExpansion)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="CoefficientOfThermalExpansion"/> to another <see cref="CoefficientOfThermalExpansion"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="CoefficientOfThermalExpansion"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(CoefficientOfThermalExpansionUnit unit, [NotNullWhen(true)] out CoefficientOfThermalExpansion? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + CoefficientOfThermalExpansion? convertedOrNull = (Unit, unit) switch + { + // CoefficientOfThermalExpansionUnit -> BaseUnit + (CoefficientOfThermalExpansionUnit.InverseDegreeCelsius, CoefficientOfThermalExpansionUnit.InverseKelvin) => new CoefficientOfThermalExpansion(_value, CoefficientOfThermalExpansionUnit.InverseKelvin), + (CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit, CoefficientOfThermalExpansionUnit.InverseKelvin) => new CoefficientOfThermalExpansion(_value * 9 / 5, CoefficientOfThermalExpansionUnit.InverseKelvin), + + // BaseUnit -> CoefficientOfThermalExpansionUnit + (CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius) => new CoefficientOfThermalExpansion(_value, CoefficientOfThermalExpansionUnit.InverseDegreeCelsius), + (CoefficientOfThermalExpansionUnit.InverseKelvin, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit) => new CoefficientOfThermalExpansion(_value * 5 / 9, CoefficientOfThermalExpansionUnit.InverseDegreeFahrenheit), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is CoefficientOfThermalExpansionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<CoefficientOfThermalExpansionUnit> IQuantity<CoefficientOfThermalExpansionUnit>.ToUnit(CoefficientOfThermalExpansionUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<CoefficientOfThermalExpansionUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(CoefficientOfThermalExpansion)) + return this; + else if (conversionType == typeof(CoefficientOfThermalExpansionUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return CoefficientOfThermalExpansion.Info; + else if (conversionType == typeof(BaseDimensions)) + return CoefficientOfThermalExpansion.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansionUnit.g.cs b/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansionUnit.g.cs new file mode 100644 index 0000000000..9b7c73ef86 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/CoefficientOfThermalExpansion/CoefficientOfThermalExpansionUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum CoefficientOfThermalExpansionUnit + { + InverseDegreeCelsius = 1, + InverseDegreeFahrenheit = 2, + InverseKelvin = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Compressibility/Compressibility.csproj b/UnitsNet.Modular/GeneratedCode/Compressibility/Compressibility.csproj new file mode 100644 index 0000000000..fc31007cfd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Compressibility/Compressibility.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Compressibility</Title> + <Description>Adds Compressibility units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>compressibility unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{daf647be-be87-88b9-ee92-dece21fe0dff}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Compressibility</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Compressibility/Compressibility.g.cs b/UnitsNet.Modular/GeneratedCode/Compressibility/Compressibility.g.cs new file mode 100644 index 0000000000..7107afe9d6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Compressibility/Compressibility.g.cs @@ -0,0 +1,964 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + [DataContract] + public readonly partial struct Compressibility : IArithmeticQuantity<Compressibility, CompressibilityUnit, double>, IEquatable<Compressibility>, IComparable, IComparable<Compressibility>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly CompressibilityUnit? _unit; + + static Compressibility() + { + BaseDimensions = new BaseDimensions(1, -1, 2, 0, 0, 0, 0); + BaseUnit = CompressibilityUnit.InversePascal; + Units = Enum.GetValues(typeof(CompressibilityUnit)).Cast<CompressibilityUnit>().ToArray(); + Zero = new Compressibility(0, BaseUnit); + Info = new QuantityInfo<CompressibilityUnit>("Compressibility", + new UnitInfo<CompressibilityUnit>[] + { + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InverseAtmosphere, "InverseAtmospheres", BaseUnits.Undefined), + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InverseBar, "InverseBars", BaseUnits.Undefined), + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InverseKilopascal, "InverseKilopascals", BaseUnits.Undefined), + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InverseMegapascal, "InverseMegapascals", BaseUnits.Undefined), + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InverseMillibar, "InverseMillibars", BaseUnits.Undefined), + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InversePascal, "InversePascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), + new UnitInfo<CompressibilityUnit>(CompressibilityUnit.InversePoundForcePerSquareInch, "InversePoundsForcePerSquareInch", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Compressibility(double value, CompressibilityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Compressibility" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<CompressibilityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Compressibility, which is InversePascal. All conversions go via this value. + /// </summary> + public static CompressibilityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Compressibility quantity. + /// </summary> + public static CompressibilityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit InversePascal. + /// </summary> + public static Compressibility Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Compressibility AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public CompressibilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<CompressibilityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Compressibility.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InverseAtmosphere"/> + /// </summary> + public double InverseAtmospheres => As(CompressibilityUnit.InverseAtmosphere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InverseBar"/> + /// </summary> + public double InverseBars => As(CompressibilityUnit.InverseBar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InverseKilopascal"/> + /// </summary> + public double InverseKilopascals => As(CompressibilityUnit.InverseKilopascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InverseMegapascal"/> + /// </summary> + public double InverseMegapascals => As(CompressibilityUnit.InverseMegapascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InverseMillibar"/> + /// </summary> + public double InverseMillibars => As(CompressibilityUnit.InverseMillibar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InversePascal"/> + /// </summary> + public double InversePascals => As(CompressibilityUnit.InversePascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="CompressibilityUnit.InversePoundForcePerSquareInch"/> + /// </summary> + public double InversePoundsForcePerSquareInch => As(CompressibilityUnit.InversePoundForcePerSquareInch); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: CompressibilityUnit -> BaseUnit + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InverseAtmosphere, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InverseBar, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InverseKilopascal, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InverseMegapascal, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InverseMillibar, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePoundForcePerSquareInch, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InversePascal, quantity => quantity); + + // Register in unit converter: BaseUnit -> CompressibilityUnit + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseAtmosphere, quantity => quantity.ToUnit(CompressibilityUnit.InverseAtmosphere)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseBar, quantity => quantity.ToUnit(CompressibilityUnit.InverseBar)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseKilopascal, quantity => quantity.ToUnit(CompressibilityUnit.InverseKilopascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMegapascal, quantity => quantity.ToUnit(CompressibilityUnit.InverseMegapascal)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMillibar, quantity => quantity.ToUnit(CompressibilityUnit.InverseMillibar)); + unitConverter.SetConversionFunction<Compressibility>(CompressibilityUnit.InversePascal, CompressibilityUnit.InversePoundForcePerSquareInch, quantity => quantity.ToUnit(CompressibilityUnit.InversePoundForcePerSquareInch)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InverseAtmosphere, new CultureInfo("en-US"), false, true, new string[]{"atm⁻¹", "1/atm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InverseBar, new CultureInfo("en-US"), false, true, new string[]{"bar⁻¹", "1/bar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InverseKilopascal, new CultureInfo("en-US"), false, true, new string[]{"kPa⁻¹", "1/kPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InverseMegapascal, new CultureInfo("en-US"), false, true, new string[]{"MPa⁻¹", "1/MPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InverseMillibar, new CultureInfo("en-US"), false, true, new string[]{"mbar⁻¹", "1/mbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InversePascal, new CultureInfo("en-US"), false, true, new string[]{"Pa⁻¹", "1/Pa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(CompressibilityUnit.InversePoundForcePerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"psi⁻¹", "1/psi"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(CompressibilityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(CompressibilityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InverseAtmosphere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInverseAtmospheres(QuantityValue inverseatmospheres) + { + double value = (double) inverseatmospheres; + return new Compressibility(value, CompressibilityUnit.InverseAtmosphere); + } + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InverseBar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInverseBars(QuantityValue inversebars) + { + double value = (double) inversebars; + return new Compressibility(value, CompressibilityUnit.InverseBar); + } + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InverseKilopascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInverseKilopascals(QuantityValue inversekilopascals) + { + double value = (double) inversekilopascals; + return new Compressibility(value, CompressibilityUnit.InverseKilopascal); + } + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InverseMegapascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInverseMegapascals(QuantityValue inversemegapascals) + { + double value = (double) inversemegapascals; + return new Compressibility(value, CompressibilityUnit.InverseMegapascal); + } + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InverseMillibar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInverseMillibars(QuantityValue inversemillibars) + { + double value = (double) inversemillibars; + return new Compressibility(value, CompressibilityUnit.InverseMillibar); + } + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InversePascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInversePascals(QuantityValue inversepascals) + { + double value = (double) inversepascals; + return new Compressibility(value, CompressibilityUnit.InversePascal); + } + + /// <summary> + /// Creates a <see cref="Compressibility"/> from <see cref="CompressibilityUnit.InversePoundForcePerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Compressibility FromInversePoundsForcePerSquareInch(QuantityValue inversepoundsforcepersquareinch) + { + double value = (double) inversepoundsforcepersquareinch; + return new Compressibility(value, CompressibilityUnit.InversePoundForcePerSquareInch); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="CompressibilityUnit" /> to <see cref="Compressibility" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Compressibility unit value.</returns> + public static Compressibility From(QuantityValue value, CompressibilityUnit fromUnit) + { + return new Compressibility((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Compressibility Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Compressibility Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Compressibility, CompressibilityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Compressibility result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Compressibility result) + { + return QuantityParser.Default.TryParse<Compressibility, CompressibilityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static CompressibilityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static CompressibilityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<CompressibilityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.CompressibilityUnit)"/> + public static bool TryParseUnit(string str, out CompressibilityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out CompressibilityUnit unit) + { + return UnitParser.Default.TryParse<CompressibilityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Compressibility operator -(Compressibility right) + { + return new Compressibility(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Compressibility"/> from adding two <see cref="Compressibility"/>.</summary> + public static Compressibility operator +(Compressibility left, Compressibility right) + { + return new Compressibility(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Compressibility"/> from subtracting two <see cref="Compressibility"/>.</summary> + public static Compressibility operator -(Compressibility left, Compressibility right) + { + return new Compressibility(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Compressibility"/> from multiplying value and <see cref="Compressibility"/>.</summary> + public static Compressibility operator *(double left, Compressibility right) + { + return new Compressibility(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Compressibility"/> from multiplying value and <see cref="Compressibility"/>.</summary> + public static Compressibility operator *(Compressibility left, double right) + { + return new Compressibility(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Compressibility"/> from dividing <see cref="Compressibility"/> by value.</summary> + public static Compressibility operator /(Compressibility left, double right) + { + return new Compressibility(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Compressibility"/> by <see cref="Compressibility"/>.</summary> + public static double operator /(Compressibility left, Compressibility right) + { + return left.InversePascals / right.InversePascals; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Compressibility left, Compressibility right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Compressibility left, Compressibility right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Compressibility left, Compressibility right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Compressibility left, Compressibility right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Compressibility"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Compressibility, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Compressibility left, Compressibility right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Compressibility"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Compressibility, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Compressibility left, Compressibility right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Compressibility"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Compressibility, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Compressibility otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Compressibility"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Compressibility, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Compressibility other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Compressibility"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Compressibility otherQuantity)) throw new ArgumentException("Expected type Compressibility.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Compressibility"/> with another <see cref="Compressibility"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Compressibility other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Compressibility within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Compressibility other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Compressibility.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(CompressibilityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is CompressibilityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Compressibility to another Compressibility with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Compressibility with the specified unit.</returns> + public Compressibility ToUnit(CompressibilityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Compressibility"/> to another <see cref="Compressibility"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Compressibility with the specified unit.</returns> + public Compressibility ToUnit(CompressibilityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Compressibility), Unit, typeof(Compressibility), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Compressibility)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Compressibility"/> to another <see cref="Compressibility"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Compressibility"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(CompressibilityUnit unit, [NotNullWhen(true)] out Compressibility? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Compressibility? convertedOrNull = (Unit, unit) switch + { + // CompressibilityUnit -> BaseUnit + (CompressibilityUnit.InverseAtmosphere, CompressibilityUnit.InversePascal) => new Compressibility(_value * 101325, CompressibilityUnit.InversePascal), + (CompressibilityUnit.InverseBar, CompressibilityUnit.InversePascal) => new Compressibility(_value * 1e5, CompressibilityUnit.InversePascal), + (CompressibilityUnit.InverseKilopascal, CompressibilityUnit.InversePascal) => new Compressibility(_value * 1e3, CompressibilityUnit.InversePascal), + (CompressibilityUnit.InverseMegapascal, CompressibilityUnit.InversePascal) => new Compressibility(_value * 1e6, CompressibilityUnit.InversePascal), + (CompressibilityUnit.InverseMillibar, CompressibilityUnit.InversePascal) => new Compressibility(_value * 100, CompressibilityUnit.InversePascal), + (CompressibilityUnit.InversePoundForcePerSquareInch, CompressibilityUnit.InversePascal) => new Compressibility(_value * 6.894757293168361e3, CompressibilityUnit.InversePascal), + + // BaseUnit -> CompressibilityUnit + (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseAtmosphere) => new Compressibility(_value / 101325, CompressibilityUnit.InverseAtmosphere), + (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseBar) => new Compressibility(_value / 1e5, CompressibilityUnit.InverseBar), + (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseKilopascal) => new Compressibility(_value / 1e3, CompressibilityUnit.InverseKilopascal), + (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMegapascal) => new Compressibility(_value / 1e6, CompressibilityUnit.InverseMegapascal), + (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMillibar) => new Compressibility(_value / 100, CompressibilityUnit.InverseMillibar), + (CompressibilityUnit.InversePascal, CompressibilityUnit.InversePoundForcePerSquareInch) => new Compressibility(_value / 6.894757293168361e3, CompressibilityUnit.InversePoundForcePerSquareInch), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is CompressibilityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<CompressibilityUnit> IQuantity<CompressibilityUnit>.ToUnit(CompressibilityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<CompressibilityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Compressibility)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Compressibility)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Compressibility)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Compressibility)) + return this; + else if (conversionType == typeof(CompressibilityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Compressibility.Info; + else if (conversionType == typeof(BaseDimensions)) + return Compressibility.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Compressibility)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Compressibility/CompressibilityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Compressibility/CompressibilityUnit.g.cs new file mode 100644 index 0000000000..c272160cf2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Compressibility/CompressibilityUnit.g.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum CompressibilityUnit + { + InverseAtmosphere = 1, + InverseBar = 2, + InverseKilopascal = 3, + InverseMegapascal = 4, + InverseMillibar = 5, + InversePascal = 6, + InversePoundForcePerSquareInch = 7, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Density/Density.csproj b/UnitsNet.Modular/GeneratedCode/Density/Density.csproj new file mode 100644 index 0000000000..6e5f568ff7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Density/Density.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Density</Title> + <Description>Adds Density units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>density unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{d683a277-5892-aec2-985d-c2343725d0af}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Density</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Density/Density.g.cs b/UnitsNet.Modular/GeneratedCode/Density/Density.g.cs new file mode 100644 index 0000000000..99ed523578 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Density/Density.g.cs @@ -0,0 +1,1895 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The density, or more precisely, the volumetric mass density, of a substance is its mass per unit volume. + /// </summary> + /// <remarks> + /// http://en.wikipedia.org/wiki/Density + /// </remarks> + [DataContract] + public readonly partial struct Density : IArithmeticQuantity<Density, DensityUnit, double>, IEquatable<Density>, IComparable, IComparable<Density>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly DensityUnit? _unit; + + static Density() + { + BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); + BaseUnit = DensityUnit.KilogramPerCubicMeter; + Units = Enum.GetValues(typeof(DensityUnit)).Cast<DensityUnit>().ToArray(); + Zero = new Density(0, BaseUnit); + Info = new QuantityInfo<DensityUnit>("Density", + new UnitInfo<DensityUnit>[] + { + new UnitInfo<DensityUnit>(DensityUnit.CentigramPerDeciliter, "CentigramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.CentigramPerLiter, "CentigramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.CentigramPerMilliliter, "CentigramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.DecigramPerDeciliter, "DecigramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.DecigramPerLiter, "DecigramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.DecigramPerMilliliter, "DecigramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.GramPerCubicCentimeter, "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)), + new UnitInfo<DensityUnit>(DensityUnit.GramPerCubicFoot, "GramsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram)), + new UnitInfo<DensityUnit>(DensityUnit.GramPerCubicInch, "GramsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Gram)), + new UnitInfo<DensityUnit>(DensityUnit.GramPerCubicMeter, "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)), + new UnitInfo<DensityUnit>(DensityUnit.GramPerCubicMillimeter, "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram)), + new UnitInfo<DensityUnit>(DensityUnit.GramPerDeciliter, "GramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.GramPerLiter, "GramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.GramPerMilliliter, "GramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.KilogramPerCubicCentimeter, "KilogramsPerCubicCentimeter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.KilogramPerCubicMeter, "KilogramsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.KilogramPerCubicMillimeter, "KilogramsPerCubicMillimeter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.KilogramPerLiter, "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram)), + new UnitInfo<DensityUnit>(DensityUnit.KilopoundPerCubicFoot, "KilopoundsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.KilopoundPerCubicInch, "KilopoundsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MicrogramPerCubicMeter, "MicrogramsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MicrogramPerDeciliter, "MicrogramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MicrogramPerLiter, "MicrogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MicrogramPerMilliliter, "MicrogramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MilligramPerCubicMeter, "MilligramsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MilligramPerDeciliter, "MilligramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MilligramPerLiter, "MilligramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.MilligramPerMilliliter, "MilligramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.NanogramPerDeciliter, "NanogramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.NanogramPerLiter, "NanogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.NanogramPerMilliliter, "NanogramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.PicogramPerDeciliter, "PicogramsPerDeciLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.PicogramPerLiter, "PicogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.PicogramPerMilliliter, "PicogramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerCubicCentimeter, "PoundsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Pound)), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerCubicFoot, "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerCubicInch, "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound)), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerCubicMeter, "PoundsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Pound)), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerCubicMillimeter, "PoundsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Pound)), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerImperialGallon, "PoundsPerImperialGallon", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.PoundPerUSGallon, "PoundsPerUSGallon", BaseUnits.Undefined), + new UnitInfo<DensityUnit>(DensityUnit.SlugPerCubicCentimeter, "SlugsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Slug)), + new UnitInfo<DensityUnit>(DensityUnit.SlugPerCubicFoot, "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug)), + new UnitInfo<DensityUnit>(DensityUnit.SlugPerCubicInch, "SlugsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug)), + new UnitInfo<DensityUnit>(DensityUnit.SlugPerCubicMeter, "SlugsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Slug)), + new UnitInfo<DensityUnit>(DensityUnit.SlugPerCubicMillimeter, "SlugsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Slug)), + new UnitInfo<DensityUnit>(DensityUnit.TonnePerCubicCentimeter, "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne)), + new UnitInfo<DensityUnit>(DensityUnit.TonnePerCubicFoot, "TonnesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Tonne)), + new UnitInfo<DensityUnit>(DensityUnit.TonnePerCubicInch, "TonnesPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Tonne)), + new UnitInfo<DensityUnit>(DensityUnit.TonnePerCubicMeter, "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)), + new UnitInfo<DensityUnit>(DensityUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Density(double value, DensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Density" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<DensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. + /// </summary> + public static DensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Density quantity. + /// </summary> + public static DensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// </summary> + public static Density Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Density AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<DensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Density.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.CentigramPerDeciliter"/> + /// </summary> + public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.CentigramPerLiter"/> + /// </summary> + public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.CentigramPerMilliliter"/> + /// </summary> + public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.DecigramPerDeciliter"/> + /// </summary> + public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.DecigramPerLiter"/> + /// </summary> + public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.DecigramPerMilliliter"/> + /// </summary> + public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerCubicCentimeter"/> + /// </summary> + public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerCubicFoot"/> + /// </summary> + public double GramsPerCubicFoot => As(DensityUnit.GramPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerCubicInch"/> + /// </summary> + public double GramsPerCubicInch => As(DensityUnit.GramPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerCubicMeter"/> + /// </summary> + public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerCubicMillimeter"/> + /// </summary> + public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerDeciliter"/> + /// </summary> + public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerLiter"/> + /// </summary> + public double GramsPerLiter => As(DensityUnit.GramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.GramPerMilliliter"/> + /// </summary> + public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.KilogramPerCubicCentimeter"/> + /// </summary> + public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.KilogramPerCubicMeter"/> + /// </summary> + public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.KilogramPerCubicMillimeter"/> + /// </summary> + public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.KilogramPerLiter"/> + /// </summary> + public double KilogramsPerLiter => As(DensityUnit.KilogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.KilopoundPerCubicFoot"/> + /// </summary> + public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.KilopoundPerCubicInch"/> + /// </summary> + public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MicrogramPerCubicMeter"/> + /// </summary> + public double MicrogramsPerCubicMeter => As(DensityUnit.MicrogramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MicrogramPerDeciliter"/> + /// </summary> + public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MicrogramPerLiter"/> + /// </summary> + public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MicrogramPerMilliliter"/> + /// </summary> + public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MilligramPerCubicMeter"/> + /// </summary> + public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MilligramPerDeciliter"/> + /// </summary> + public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MilligramPerLiter"/> + /// </summary> + public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.MilligramPerMilliliter"/> + /// </summary> + public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.NanogramPerDeciliter"/> + /// </summary> + public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.NanogramPerLiter"/> + /// </summary> + public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.NanogramPerMilliliter"/> + /// </summary> + public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PicogramPerDeciliter"/> + /// </summary> + public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PicogramPerLiter"/> + /// </summary> + public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PicogramPerMilliliter"/> + /// </summary> + public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerCubicCentimeter"/> + /// </summary> + public double PoundsPerCubicCentimeter => As(DensityUnit.PoundPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerCubicFoot"/> + /// </summary> + public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerCubicInch"/> + /// </summary> + public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerCubicMeter"/> + /// </summary> + public double PoundsPerCubicMeter => As(DensityUnit.PoundPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerCubicMillimeter"/> + /// </summary> + public double PoundsPerCubicMillimeter => As(DensityUnit.PoundPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerImperialGallon"/> + /// </summary> + public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.PoundPerUSGallon"/> + /// </summary> + public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.SlugPerCubicCentimeter"/> + /// </summary> + public double SlugsPerCubicCentimeter => As(DensityUnit.SlugPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.SlugPerCubicFoot"/> + /// </summary> + public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.SlugPerCubicInch"/> + /// </summary> + public double SlugsPerCubicInch => As(DensityUnit.SlugPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.SlugPerCubicMeter"/> + /// </summary> + public double SlugsPerCubicMeter => As(DensityUnit.SlugPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.SlugPerCubicMillimeter"/> + /// </summary> + public double SlugsPerCubicMillimeter => As(DensityUnit.SlugPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.TonnePerCubicCentimeter"/> + /// </summary> + public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.TonnePerCubicFoot"/> + /// </summary> + public double TonnesPerCubicFoot => As(DensityUnit.TonnePerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.TonnePerCubicInch"/> + /// </summary> + public double TonnesPerCubicInch => As(DensityUnit.TonnePerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.TonnePerCubicMeter"/> + /// </summary> + public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DensityUnit.TonnePerCubicMillimeter"/> + /// </summary> + public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: DensityUnit -> BaseUnit + unitConverter.SetConversionFunction<Density>(DensityUnit.CentigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.CentigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.CentigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.DecigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.DecigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.DecigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.GramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilopoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilopoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MicrogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MicrogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MicrogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MicrogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MilligramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MilligramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MilligramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.MilligramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.NanogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.NanogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.NanogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PicogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PicogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PicogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerImperialGallon, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.SlugPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.SlugPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.SlugPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.SlugPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.SlugPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.TonnePerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.TonnePerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.TonnePerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.TonnePerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.TonnePerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> DensityUnit + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.CentigramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerLiter, quantity => quantity.ToUnit(DensityUnit.CentigramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.CentigramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.DecigramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerLiter, quantity => quantity.ToUnit(DensityUnit.DecigramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.DecigramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicCentimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.GramPerCubicFoot)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicInch, quantity => quantity.ToUnit(DensityUnit.GramPerCubicInch)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicMillimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.GramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerLiter, quantity => quantity.ToUnit(DensityUnit.GramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.GramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicCentimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMillimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerLiter, quantity => quantity.ToUnit(DensityUnit.KilogramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicFoot)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicInch, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicInch)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerLiter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.MilligramPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.MilligramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerLiter, quantity => quantity.ToUnit(DensityUnit.MilligramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.MilligramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.NanogramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerLiter, quantity => quantity.ToUnit(DensityUnit.NanogramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.NanogramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.PicogramPerDeciliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerLiter, quantity => quantity.ToUnit(DensityUnit.PicogramPerLiter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.PicogramPerMilliliter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicCentimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicFoot)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicInch, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicInch)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicMillimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerImperialGallon, quantity => quantity.ToUnit(DensityUnit.PoundPerImperialGallon)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerUSGallon, quantity => quantity.ToUnit(DensityUnit.PoundPerUSGallon)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicCentimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicFoot)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicInch, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicInch)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicMillimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicCentimeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicFoot, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicFoot)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicInch, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicInch)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicMeter)); + unitConverter.SetConversionFunction<Density>(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.CentigramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"cg/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.CentigramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"cg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.CentigramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"cg/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.DecigramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"dg/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.DecigramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"dg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.DecigramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"dg/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"g/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"g/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"g/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"g/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"г/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"g/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"g/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"g/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.GramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"g/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilogramPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kg/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilogramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kg/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilogramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кг/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilogramPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kg/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"kg/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilopoundPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"kip/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.KilopoundPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"kip/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MicrogramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"µg/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MicrogramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"мкг/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MicrogramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"µg/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MicrogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"µg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MicrogramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"µg/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MilligramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"mg/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MilligramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"мг/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MilligramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"mg/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MilligramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"mg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.MilligramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"mg/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.NanogramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"ng/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.NanogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"ng/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.NanogramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"ng/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PicogramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"pg/dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PicogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"pg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PicogramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"pg/ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"lb/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"lb/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"lb/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"lb/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"lb/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerImperialGallon, new CultureInfo("en-US"), false, true, new string[]{"ppg (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.PoundPerUSGallon, new CultureInfo("en-US"), false, true, new string[]{"ppg (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.SlugPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"slug/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.SlugPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"slug/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.SlugPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"slug/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.SlugPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"slug/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.SlugPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"slug/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.TonnePerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"t/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.TonnePerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"t/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.TonnePerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"t/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.TonnePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"t/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DensityUnit.TonnePerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"t/mm³"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(DensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(DensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.CentigramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) + { + double value = (double) centigramsperdeciliter; + return new Density(value, DensityUnit.CentigramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.CentigramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) + { + double value = (double) centigramsperliter; + return new Density(value, DensityUnit.CentigramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.CentigramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) + { + double value = (double) centigramspermilliliter; + return new Density(value, DensityUnit.CentigramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.DecigramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) + { + double value = (double) decigramsperdeciliter; + return new Density(value, DensityUnit.DecigramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.DecigramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) + { + double value = (double) decigramsperliter; + return new Density(value, DensityUnit.DecigramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.DecigramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) + { + double value = (double) decigramspermilliliter; + return new Density(value, DensityUnit.DecigramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) + { + double value = (double) gramspercubiccentimeter; + return new Density(value, DensityUnit.GramPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerCubicFoot(QuantityValue gramspercubicfoot) + { + double value = (double) gramspercubicfoot; + return new Density(value, DensityUnit.GramPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerCubicInch(QuantityValue gramspercubicinch) + { + double value = (double) gramspercubicinch; + return new Density(value, DensityUnit.GramPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) + { + double value = (double) gramspercubicmeter; + return new Density(value, DensityUnit.GramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) + { + double value = (double) gramspercubicmillimeter; + return new Density(value, DensityUnit.GramPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) + { + double value = (double) gramsperdeciliter; + return new Density(value, DensityUnit.GramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerLiter(QuantityValue gramsperliter) + { + double value = (double) gramsperliter; + return new Density(value, DensityUnit.GramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.GramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) + { + double value = (double) gramspermilliliter; + return new Density(value, DensityUnit.GramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.KilogramPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) + { + double value = (double) kilogramspercubiccentimeter; + return new Density(value, DensityUnit.KilogramPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.KilogramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) + { + double value = (double) kilogramspercubicmeter; + return new Density(value, DensityUnit.KilogramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.KilogramPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) + { + double value = (double) kilogramspercubicmillimeter; + return new Density(value, DensityUnit.KilogramPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.KilogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromKilogramsPerLiter(QuantityValue kilogramsperliter) + { + double value = (double) kilogramsperliter; + return new Density(value, DensityUnit.KilogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.KilopoundPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) + { + double value = (double) kilopoundspercubicfoot; + return new Density(value, DensityUnit.KilopoundPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.KilopoundPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) + { + double value = (double) kilopoundspercubicinch; + return new Density(value, DensityUnit.KilopoundPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MicrogramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMicrogramsPerCubicMeter(QuantityValue microgramspercubicmeter) + { + double value = (double) microgramspercubicmeter; + return new Density(value, DensityUnit.MicrogramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MicrogramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) + { + double value = (double) microgramsperdeciliter; + return new Density(value, DensityUnit.MicrogramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MicrogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) + { + double value = (double) microgramsperliter; + return new Density(value, DensityUnit.MicrogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MicrogramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) + { + double value = (double) microgramspermilliliter; + return new Density(value, DensityUnit.MicrogramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MilligramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) + { + double value = (double) milligramspercubicmeter; + return new Density(value, DensityUnit.MilligramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MilligramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) + { + double value = (double) milligramsperdeciliter; + return new Density(value, DensityUnit.MilligramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MilligramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) + { + double value = (double) milligramsperliter; + return new Density(value, DensityUnit.MilligramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.MilligramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) + { + double value = (double) milligramspermilliliter; + return new Density(value, DensityUnit.MilligramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.NanogramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) + { + double value = (double) nanogramsperdeciliter; + return new Density(value, DensityUnit.NanogramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.NanogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) + { + double value = (double) nanogramsperliter; + return new Density(value, DensityUnit.NanogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.NanogramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) + { + double value = (double) nanogramspermilliliter; + return new Density(value, DensityUnit.NanogramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PicogramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) + { + double value = (double) picogramsperdeciliter; + return new Density(value, DensityUnit.PicogramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PicogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) + { + double value = (double) picogramsperliter; + return new Density(value, DensityUnit.PicogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PicogramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) + { + double value = (double) picogramspermilliliter; + return new Density(value, DensityUnit.PicogramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerCubicCentimeter(QuantityValue poundspercubiccentimeter) + { + double value = (double) poundspercubiccentimeter; + return new Density(value, DensityUnit.PoundPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) + { + double value = (double) poundspercubicfoot; + return new Density(value, DensityUnit.PoundPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) + { + double value = (double) poundspercubicinch; + return new Density(value, DensityUnit.PoundPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerCubicMeter(QuantityValue poundspercubicmeter) + { + double value = (double) poundspercubicmeter; + return new Density(value, DensityUnit.PoundPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerCubicMillimeter(QuantityValue poundspercubicmillimeter) + { + double value = (double) poundspercubicmillimeter; + return new Density(value, DensityUnit.PoundPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerImperialGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) + { + double value = (double) poundsperimperialgallon; + return new Density(value, DensityUnit.PoundPerImperialGallon); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.PoundPerUSGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) + { + double value = (double) poundsperusgallon; + return new Density(value, DensityUnit.PoundPerUSGallon); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.SlugPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromSlugsPerCubicCentimeter(QuantityValue slugspercubiccentimeter) + { + double value = (double) slugspercubiccentimeter; + return new Density(value, DensityUnit.SlugPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.SlugPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) + { + double value = (double) slugspercubicfoot; + return new Density(value, DensityUnit.SlugPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.SlugPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromSlugsPerCubicInch(QuantityValue slugspercubicinch) + { + double value = (double) slugspercubicinch; + return new Density(value, DensityUnit.SlugPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.SlugPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromSlugsPerCubicMeter(QuantityValue slugspercubicmeter) + { + double value = (double) slugspercubicmeter; + return new Density(value, DensityUnit.SlugPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.SlugPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromSlugsPerCubicMillimeter(QuantityValue slugspercubicmillimeter) + { + double value = (double) slugspercubicmillimeter; + return new Density(value, DensityUnit.SlugPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.TonnePerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) + { + double value = (double) tonnespercubiccentimeter; + return new Density(value, DensityUnit.TonnePerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.TonnePerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromTonnesPerCubicFoot(QuantityValue tonnespercubicfoot) + { + double value = (double) tonnespercubicfoot; + return new Density(value, DensityUnit.TonnePerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.TonnePerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromTonnesPerCubicInch(QuantityValue tonnespercubicinch) + { + double value = (double) tonnespercubicinch; + return new Density(value, DensityUnit.TonnePerCubicInch); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.TonnePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) + { + double value = (double) tonnespercubicmeter; + return new Density(value, DensityUnit.TonnePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Density"/> from <see cref="DensityUnit.TonnePerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) + { + double value = (double) tonnespercubicmillimeter; + return new Density(value, DensityUnit.TonnePerCubicMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="DensityUnit" /> to <see cref="Density" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Density unit value.</returns> + public static Density From(QuantityValue value, DensityUnit fromUnit) + { + return new Density((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Density Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Density Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Density, DensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Density result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Density result) + { + return QuantityParser.Default.TryParse<Density, DensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static DensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static DensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<DensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.DensityUnit)"/> + public static bool TryParseUnit(string str, out DensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out DensityUnit unit) + { + return UnitParser.Default.TryParse<DensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Density operator -(Density right) + { + return new Density(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Density"/> from adding two <see cref="Density"/>.</summary> + public static Density operator +(Density left, Density right) + { + return new Density(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Density"/> from subtracting two <see cref="Density"/>.</summary> + public static Density operator -(Density left, Density right) + { + return new Density(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Density"/> from multiplying value and <see cref="Density"/>.</summary> + public static Density operator *(double left, Density right) + { + return new Density(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Density"/> from multiplying value and <see cref="Density"/>.</summary> + public static Density operator *(Density left, double right) + { + return new Density(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Density"/> from dividing <see cref="Density"/> by value.</summary> + public static Density operator /(Density left, double right) + { + return new Density(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Density"/> by <see cref="Density"/>.</summary> + public static double operator /(Density left, Density right) + { + return left.KilogramsPerCubicMeter / right.KilogramsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Density left, Density right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Density left, Density right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Density left, Density right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Density left, Density right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Density"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Density, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Density left, Density right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Density"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Density, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Density left, Density right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Density"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Density, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Density otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Density"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Density, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Density other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Density"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Density otherQuantity)) throw new ArgumentException("Expected type Density.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Density"/> with another <see cref="Density"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Density other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Density within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Density.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(DensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is DensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Density to another Density with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Density with the specified unit.</returns> + public Density ToUnit(DensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Density"/> to another <see cref="Density"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Density with the specified unit.</returns> + public Density ToUnit(DensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Density), Unit, typeof(Density), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Density)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Density"/> to another <see cref="Density"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Density"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(DensityUnit unit, [NotNullWhen(true)] out Density? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Density? convertedOrNull = (Unit, unit) switch + { + // DensityUnit -> BaseUnit + (DensityUnit.CentigramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-2d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.CentigramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-2d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.CentigramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-2d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.DecigramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-1d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.DecigramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-1d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.DecigramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-1d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-3, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.0353146667214886, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 61.0237440947323, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e3, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-6, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-1, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.GramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-3, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.KilogramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.KilogramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-6) * 1e3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.KilogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 1e3, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.KilopoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 0.062427961) * 1e3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.KilopoundPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 3.6127298147753e-5) * 1e3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MicrogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e3) * 1e-6d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MicrogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-6d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MicrogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-6d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MicrogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-6d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MilligramPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e3) * 1e-3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MilligramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MilligramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.MilligramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-3d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.NanogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-9d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.NanogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-9d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.NanogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-9d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PicogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-12d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PicogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-12d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PicogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-12d, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 2.204622621848775e-6, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 0.062427961, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 3.6127298147753e-5, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 2.204622621848775, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 2.204622621848775e-9, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerImperialGallon, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 9.9776398e1, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 1.19826427e2, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.SlugPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 14593903, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.SlugPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 515.378818, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.SlugPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 890574.60201535, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.SlugPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 14.5939, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.SlugPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 14593903000, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.TonnePerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-9, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.TonnePerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 3.53146667214886e4, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.TonnePerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 6.10237440947323e7, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.TonnePerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 0.001, DensityUnit.KilogramPerCubicMeter), + (DensityUnit.TonnePerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-12, DensityUnit.KilogramPerCubicMeter), + + // BaseUnit -> DensityUnit + (DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerDeciliter) => new Density((_value * 1e-1) / 1e-2d, DensityUnit.CentigramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerLiter) => new Density((_value * 1) / 1e-2d, DensityUnit.CentigramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerMilliliter) => new Density((_value * 1e-3) / 1e-2d, DensityUnit.CentigramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerDeciliter) => new Density((_value * 1e-1) / 1e-1d, DensityUnit.DecigramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerLiter) => new Density((_value * 1) / 1e-1d, DensityUnit.DecigramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerMilliliter) => new Density((_value * 1e-3) / 1e-1d, DensityUnit.DecigramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicCentimeter) => new Density(_value * 1e-3, DensityUnit.GramPerCubicCentimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicFoot) => new Density(_value / 0.0353146667214886, DensityUnit.GramPerCubicFoot), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicInch) => new Density(_value / 61.0237440947323, DensityUnit.GramPerCubicInch), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMeter) => new Density(_value * 1e3, DensityUnit.GramPerCubicMeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMillimeter) => new Density(_value * 1e-6, DensityUnit.GramPerCubicMillimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerDeciliter) => new Density(_value * 1e-1, DensityUnit.GramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerLiter) => new Density(_value * 1, DensityUnit.GramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerMilliliter) => new Density(_value * 1e-3, DensityUnit.GramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicCentimeter) => new Density((_value * 1e-3) / 1e3d, DensityUnit.KilogramPerCubicCentimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMillimeter) => new Density((_value * 1e-6) / 1e3d, DensityUnit.KilogramPerCubicMillimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerLiter) => new Density(_value / 1e3, DensityUnit.KilogramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicFoot) => new Density((_value * 0.062427961) / 1e3d, DensityUnit.KilopoundPerCubicFoot), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicInch) => new Density((_value * 3.6127298147753e-5) / 1e3d, DensityUnit.KilopoundPerCubicInch), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerCubicMeter) => new Density((_value * 1e3) / 1e-6d, DensityUnit.MicrogramPerCubicMeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerDeciliter) => new Density((_value * 1e-1) / 1e-6d, DensityUnit.MicrogramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerLiter) => new Density((_value * 1) / 1e-6d, DensityUnit.MicrogramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerMilliliter) => new Density((_value * 1e-3) / 1e-6d, DensityUnit.MicrogramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerCubicMeter) => new Density((_value * 1e3) / 1e-3d, DensityUnit.MilligramPerCubicMeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerDeciliter) => new Density((_value * 1e-1) / 1e-3d, DensityUnit.MilligramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerLiter) => new Density((_value * 1) / 1e-3d, DensityUnit.MilligramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerMilliliter) => new Density((_value * 1e-3) / 1e-3d, DensityUnit.MilligramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerDeciliter) => new Density((_value * 1e-1) / 1e-9d, DensityUnit.NanogramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerLiter) => new Density((_value * 1) / 1e-9d, DensityUnit.NanogramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerMilliliter) => new Density((_value * 1e-3) / 1e-9d, DensityUnit.NanogramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerDeciliter) => new Density((_value * 1e-1) / 1e-12d, DensityUnit.PicogramPerDeciliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerLiter) => new Density((_value * 1) / 1e-12d, DensityUnit.PicogramPerLiter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerMilliliter) => new Density((_value * 1e-3) / 1e-12d, DensityUnit.PicogramPerMilliliter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicCentimeter) => new Density(_value * 2.204622621848775e-6, DensityUnit.PoundPerCubicCentimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicFoot) => new Density(_value * 0.062427961, DensityUnit.PoundPerCubicFoot), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicInch) => new Density(_value * 3.6127298147753e-5, DensityUnit.PoundPerCubicInch), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMeter) => new Density(_value * 2.204622621848775, DensityUnit.PoundPerCubicMeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMillimeter) => new Density(_value * 2.204622621848775e-9, DensityUnit.PoundPerCubicMillimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerImperialGallon) => new Density(_value / 9.9776398e1, DensityUnit.PoundPerImperialGallon), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerUSGallon) => new Density(_value / 1.19826427e2, DensityUnit.PoundPerUSGallon), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicCentimeter) => new Density(_value / 14593903, DensityUnit.SlugPerCubicCentimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicFoot) => new Density(_value * 0.00194032033, DensityUnit.SlugPerCubicFoot), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicInch) => new Density(_value / 890574.60201535, DensityUnit.SlugPerCubicInch), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMeter) => new Density(_value / 14.5939, DensityUnit.SlugPerCubicMeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMillimeter) => new Density(_value / 14593903000, DensityUnit.SlugPerCubicMillimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicCentimeter) => new Density(_value * 1e-9, DensityUnit.TonnePerCubicCentimeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicFoot) => new Density(_value / 3.53146667214886e4, DensityUnit.TonnePerCubicFoot), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicInch) => new Density(_value / 6.10237440947323e7, DensityUnit.TonnePerCubicInch), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMeter) => new Density(_value * 0.001, DensityUnit.TonnePerCubicMeter), + (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMillimeter) => new Density(_value * 1e-12, DensityUnit.TonnePerCubicMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is DensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<DensityUnit> IQuantity<DensityUnit>.ToUnit(DensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<DensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Density)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Density)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Density)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Density)) + return this; + else if (conversionType == typeof(DensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Density.Info; + else if (conversionType == typeof(BaseDimensions)) + return Density.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Density)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Density/DensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Density/DensityUnit.g.cs new file mode 100644 index 0000000000..a1c2aaa2d3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Density/DensityUnit.g.cs @@ -0,0 +1,82 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum DensityUnit + { + CentigramPerDeciliter = 1, + CentigramPerLiter = 2, + CentigramPerMilliliter = 3, + DecigramPerDeciliter = 4, + DecigramPerLiter = 5, + DecigramPerMilliliter = 6, + GramPerCubicCentimeter = 7, + GramPerCubicFoot = 8, + GramPerCubicInch = 9, + GramPerCubicMeter = 10, + GramPerCubicMillimeter = 11, + GramPerDeciliter = 12, + GramPerLiter = 13, + GramPerMilliliter = 14, + KilogramPerCubicCentimeter = 15, + KilogramPerCubicMeter = 16, + KilogramPerCubicMillimeter = 17, + KilogramPerLiter = 18, + KilopoundPerCubicFoot = 19, + KilopoundPerCubicInch = 20, + MicrogramPerCubicMeter = 21, + MicrogramPerDeciliter = 22, + MicrogramPerLiter = 23, + MicrogramPerMilliliter = 24, + MilligramPerCubicMeter = 25, + MilligramPerDeciliter = 26, + MilligramPerLiter = 27, + MilligramPerMilliliter = 28, + NanogramPerDeciliter = 29, + NanogramPerLiter = 30, + NanogramPerMilliliter = 31, + PicogramPerDeciliter = 32, + PicogramPerLiter = 33, + PicogramPerMilliliter = 34, + PoundPerCubicCentimeter = 35, + PoundPerCubicFoot = 36, + PoundPerCubicInch = 37, + PoundPerCubicMeter = 38, + PoundPerCubicMillimeter = 39, + PoundPerImperialGallon = 40, + PoundPerUSGallon = 41, + SlugPerCubicCentimeter = 42, + SlugPerCubicFoot = 43, + SlugPerCubicInch = 44, + SlugPerCubicMeter = 45, + SlugPerCubicMillimeter = 46, + TonnePerCubicCentimeter = 47, + TonnePerCubicFoot = 48, + TonnePerCubicInch = 49, + TonnePerCubicMeter = 50, + TonnePerCubicMillimeter = 51, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Duration/Duration.csproj b/UnitsNet.Modular/GeneratedCode/Duration/Duration.csproj new file mode 100644 index 0000000000..2091e87634 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Duration/Duration.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Duration</Title> + <Description>Adds Duration units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>duration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{3c2ac54f-554c-518b-7c46-3b22d86d0e3b}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Duration</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Duration/Duration.g.cs b/UnitsNet.Modular/GeneratedCode/Duration/Duration.g.cs new file mode 100644 index 0000000000..ae4e291d0f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Duration/Duration.g.cs @@ -0,0 +1,1058 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Duration : IArithmeticQuantity<Duration, DurationUnit, double>, IEquatable<Duration>, IComparable, IComparable<Duration>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly DurationUnit? _unit; + + static Duration() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); + BaseUnit = DurationUnit.Second; + Units = Enum.GetValues(typeof(DurationUnit)).Cast<DurationUnit>().ToArray(); + Zero = new Duration(0, BaseUnit); + Info = new QuantityInfo<DurationUnit>("Duration", + new UnitInfo<DurationUnit>[] + { + new UnitInfo<DurationUnit>(DurationUnit.Day, "Days", new BaseUnits(time: DurationUnit.Day)), + new UnitInfo<DurationUnit>(DurationUnit.Hour, "Hours", new BaseUnits(time: DurationUnit.Hour)), + new UnitInfo<DurationUnit>(DurationUnit.JulianYear, "JulianYears", new BaseUnits(time: DurationUnit.JulianYear)), + new UnitInfo<DurationUnit>(DurationUnit.Microsecond, "Microseconds", BaseUnits.Undefined), + new UnitInfo<DurationUnit>(DurationUnit.Millisecond, "Milliseconds", BaseUnits.Undefined), + new UnitInfo<DurationUnit>(DurationUnit.Minute, "Minutes", new BaseUnits(time: DurationUnit.Minute)), + new UnitInfo<DurationUnit>(DurationUnit.Month30, "Months30", new BaseUnits(time: DurationUnit.Month30)), + new UnitInfo<DurationUnit>(DurationUnit.Nanosecond, "Nanoseconds", BaseUnits.Undefined), + new UnitInfo<DurationUnit>(DurationUnit.Second, "Seconds", new BaseUnits(time: DurationUnit.Second)), + new UnitInfo<DurationUnit>(DurationUnit.Week, "Weeks", new BaseUnits(time: DurationUnit.Week)), + new UnitInfo<DurationUnit>(DurationUnit.Year365, "Years365", new BaseUnits(time: DurationUnit.Year365)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Duration(double value, DurationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Duration" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<DurationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Duration, which is Second. All conversions go via this value. + /// </summary> + public static DurationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Duration quantity. + /// </summary> + public static DurationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// </summary> + public static Duration Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Duration AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<DurationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Duration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Day"/> + /// </summary> + public double Days => As(DurationUnit.Day); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Hour"/> + /// </summary> + public double Hours => As(DurationUnit.Hour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.JulianYear"/> + /// </summary> + public double JulianYears => As(DurationUnit.JulianYear); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Microsecond"/> + /// </summary> + public double Microseconds => As(DurationUnit.Microsecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Millisecond"/> + /// </summary> + public double Milliseconds => As(DurationUnit.Millisecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Minute"/> + /// </summary> + public double Minutes => As(DurationUnit.Minute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Month30"/> + /// </summary> + public double Months30 => As(DurationUnit.Month30); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Nanosecond"/> + /// </summary> + public double Nanoseconds => As(DurationUnit.Nanosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Second"/> + /// </summary> + public double Seconds => As(DurationUnit.Second); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Week"/> + /// </summary> + public double Weeks => As(DurationUnit.Week); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DurationUnit.Year365"/> + /// </summary> + public double Years365 => As(DurationUnit.Year365); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: DurationUnit -> BaseUnit + unitConverter.SetConversionFunction<Duration>(DurationUnit.Day, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Hour, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.JulianYear, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Microsecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Millisecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Minute, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Month30, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Nanosecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Week, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Year365, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Second, quantity => quantity); + + // Register in unit converter: BaseUnit -> DurationUnit + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Day, quantity => quantity.ToUnit(DurationUnit.Day)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Hour, quantity => quantity.ToUnit(DurationUnit.Hour)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.JulianYear, quantity => quantity.ToUnit(DurationUnit.JulianYear)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Microsecond, quantity => quantity.ToUnit(DurationUnit.Microsecond)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Millisecond, quantity => quantity.ToUnit(DurationUnit.Millisecond)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Minute, quantity => quantity.ToUnit(DurationUnit.Minute)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Month30, quantity => quantity.ToUnit(DurationUnit.Month30)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Nanosecond, quantity => quantity.ToUnit(DurationUnit.Nanosecond)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Week, quantity => quantity.ToUnit(DurationUnit.Week)); + unitConverter.SetConversionFunction<Duration>(DurationUnit.Second, DurationUnit.Year365, quantity => quantity.ToUnit(DurationUnit.Year365)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Day, new CultureInfo("en-US"), false, true, new string[]{"d", "day", "days"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Day, new CultureInfo("ru-RU"), false, true, new string[]{"сут", "д"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Hour, new CultureInfo("en-US"), false, true, new string[]{"h", "hr", "hrs", "hour", "hours"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Hour, new CultureInfo("ru-RU"), false, true, new string[]{"ч", "час"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.JulianYear, new CultureInfo("en-US"), false, true, new string[]{"jyr", "jyear", "jyears"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Microsecond, new CultureInfo("en-US"), false, true, new string[]{"µs", "µsec", "µsecs", "µsecond", "µseconds"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Microsecond, new CultureInfo("ru-RU"), false, true, new string[]{"мксек", "мкс"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Millisecond, new CultureInfo("en-US"), false, true, new string[]{"ms", "msec", "msecs", "msecond", "mseconds"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Millisecond, new CultureInfo("ru-RU"), false, true, new string[]{"мсек", "мс"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Minute, new CultureInfo("en-US"), false, true, new string[]{"m", "min", "minute", "minutes"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Minute, new CultureInfo("ru-RU"), false, true, new string[]{"мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Month30, new CultureInfo("en-US"), false, true, new string[]{"mo", "month", "months"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Month30, new CultureInfo("ru-RU"), false, true, new string[]{"месяц"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Nanosecond, new CultureInfo("en-US"), false, true, new string[]{"ns", "nsec", "nsecs", "nsecond", "nseconds"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Nanosecond, new CultureInfo("ru-RU"), false, true, new string[]{"нсек", "нс"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Second, new CultureInfo("en-US"), false, true, new string[]{"s", "sec", "secs", "second", "seconds"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Second, new CultureInfo("ru-RU"), false, true, new string[]{"сек", "с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Week, new CultureInfo("en-US"), false, true, new string[]{"wk", "week", "weeks"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Week, new CultureInfo("ru-RU"), false, true, new string[]{"нед"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Year365, new CultureInfo("en-US"), false, true, new string[]{"yr", "year", "years"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DurationUnit.Year365, new CultureInfo("ru-RU"), false, true, new string[]{"год"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(DurationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(DurationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Day"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromDays(QuantityValue days) + { + double value = (double) days; + return new Duration(value, DurationUnit.Day); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Hour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromHours(QuantityValue hours) + { + double value = (double) hours; + return new Duration(value, DurationUnit.Hour); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.JulianYear"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromJulianYears(QuantityValue julianyears) + { + double value = (double) julianyears; + return new Duration(value, DurationUnit.JulianYear); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Microsecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromMicroseconds(QuantityValue microseconds) + { + double value = (double) microseconds; + return new Duration(value, DurationUnit.Microsecond); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Millisecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromMilliseconds(QuantityValue milliseconds) + { + double value = (double) milliseconds; + return new Duration(value, DurationUnit.Millisecond); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Minute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromMinutes(QuantityValue minutes) + { + double value = (double) minutes; + return new Duration(value, DurationUnit.Minute); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Month30"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromMonths30(QuantityValue months30) + { + double value = (double) months30; + return new Duration(value, DurationUnit.Month30); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Nanosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromNanoseconds(QuantityValue nanoseconds) + { + double value = (double) nanoseconds; + return new Duration(value, DurationUnit.Nanosecond); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Second"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromSeconds(QuantityValue seconds) + { + double value = (double) seconds; + return new Duration(value, DurationUnit.Second); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Week"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromWeeks(QuantityValue weeks) + { + double value = (double) weeks; + return new Duration(value, DurationUnit.Week); + } + + /// <summary> + /// Creates a <see cref="Duration"/> from <see cref="DurationUnit.Year365"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Duration FromYears365(QuantityValue years365) + { + double value = (double) years365; + return new Duration(value, DurationUnit.Year365); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="DurationUnit" /> to <see cref="Duration" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Duration unit value.</returns> + public static Duration From(QuantityValue value, DurationUnit fromUnit) + { + return new Duration((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Duration Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Duration Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Duration, DurationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Duration result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Duration result) + { + return QuantityParser.Default.TryParse<Duration, DurationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static DurationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static DurationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<DurationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.DurationUnit)"/> + public static bool TryParseUnit(string str, out DurationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out DurationUnit unit) + { + return UnitParser.Default.TryParse<DurationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Duration operator -(Duration right) + { + return new Duration(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Duration"/> from adding two <see cref="Duration"/>.</summary> + public static Duration operator +(Duration left, Duration right) + { + return new Duration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Duration"/> from subtracting two <see cref="Duration"/>.</summary> + public static Duration operator -(Duration left, Duration right) + { + return new Duration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Duration"/> from multiplying value and <see cref="Duration"/>.</summary> + public static Duration operator *(double left, Duration right) + { + return new Duration(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Duration"/> from multiplying value and <see cref="Duration"/>.</summary> + public static Duration operator *(Duration left, double right) + { + return new Duration(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Duration"/> from dividing <see cref="Duration"/> by value.</summary> + public static Duration operator /(Duration left, double right) + { + return new Duration(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Duration"/> by <see cref="Duration"/>.</summary> + public static double operator /(Duration left, Duration right) + { + return left.Seconds / right.Seconds; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Duration left, Duration right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Duration left, Duration right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Duration left, Duration right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Duration left, Duration right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Duration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Duration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Duration left, Duration right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Duration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Duration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Duration left, Duration right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Duration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Duration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Duration otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Duration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Duration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Duration other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Duration"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Duration otherQuantity)) throw new ArgumentException("Expected type Duration.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Duration"/> with another <see cref="Duration"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Duration other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Duration within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Duration.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(DurationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is DurationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Duration to another Duration with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Duration with the specified unit.</returns> + public Duration ToUnit(DurationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Duration"/> to another <see cref="Duration"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Duration with the specified unit.</returns> + public Duration ToUnit(DurationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Duration), Unit, typeof(Duration), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Duration)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Duration"/> to another <see cref="Duration"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Duration"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(DurationUnit unit, [NotNullWhen(true)] out Duration? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Duration? convertedOrNull = (Unit, unit) switch + { + // DurationUnit -> BaseUnit + (DurationUnit.Day, DurationUnit.Second) => new Duration(_value * 24 * 3600, DurationUnit.Second), + (DurationUnit.Hour, DurationUnit.Second) => new Duration(_value * 3600, DurationUnit.Second), + (DurationUnit.JulianYear, DurationUnit.Second) => new Duration(_value * 365.25 * 24 * 3600, DurationUnit.Second), + (DurationUnit.Microsecond, DurationUnit.Second) => new Duration((_value) * 1e-6d, DurationUnit.Second), + (DurationUnit.Millisecond, DurationUnit.Second) => new Duration((_value) * 1e-3d, DurationUnit.Second), + (DurationUnit.Minute, DurationUnit.Second) => new Duration(_value * 60, DurationUnit.Second), + (DurationUnit.Month30, DurationUnit.Second) => new Duration(_value * 30 * 24 * 3600, DurationUnit.Second), + (DurationUnit.Nanosecond, DurationUnit.Second) => new Duration((_value) * 1e-9d, DurationUnit.Second), + (DurationUnit.Week, DurationUnit.Second) => new Duration(_value * 7 * 24 * 3600, DurationUnit.Second), + (DurationUnit.Year365, DurationUnit.Second) => new Duration(_value * 365 * 24 * 3600, DurationUnit.Second), + + // BaseUnit -> DurationUnit + (DurationUnit.Second, DurationUnit.Day) => new Duration(_value / (24 * 3600), DurationUnit.Day), + (DurationUnit.Second, DurationUnit.Hour) => new Duration(_value / 3600, DurationUnit.Hour), + (DurationUnit.Second, DurationUnit.JulianYear) => new Duration(_value / (365.25 * 24 * 3600), DurationUnit.JulianYear), + (DurationUnit.Second, DurationUnit.Microsecond) => new Duration((_value) / 1e-6d, DurationUnit.Microsecond), + (DurationUnit.Second, DurationUnit.Millisecond) => new Duration((_value) / 1e-3d, DurationUnit.Millisecond), + (DurationUnit.Second, DurationUnit.Minute) => new Duration(_value / 60, DurationUnit.Minute), + (DurationUnit.Second, DurationUnit.Month30) => new Duration(_value / (30 * 24 * 3600), DurationUnit.Month30), + (DurationUnit.Second, DurationUnit.Nanosecond) => new Duration((_value) / 1e-9d, DurationUnit.Nanosecond), + (DurationUnit.Second, DurationUnit.Week) => new Duration(_value / (7 * 24 * 3600), DurationUnit.Week), + (DurationUnit.Second, DurationUnit.Year365) => new Duration(_value / (365 * 24 * 3600), DurationUnit.Year365), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is DurationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<DurationUnit> IQuantity<DurationUnit>.ToUnit(DurationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<DurationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Duration)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Duration)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Duration)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Duration)) + return this; + else if (conversionType == typeof(DurationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Duration.Info; + else if (conversionType == typeof(BaseDimensions)) + return Duration.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Duration)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Duration/DurationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Duration/DurationUnit.g.cs new file mode 100644 index 0000000000..6c6aab7c78 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Duration/DurationUnit.g.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum DurationUnit + { + Day = 1, + Hour = 2, + JulianYear = 3, + Microsecond = 4, + Millisecond = 5, + Minute = 6, + Month30 = 7, + Nanosecond = 8, + Second = 9, + Week = 10, + Year365 = 11, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosity.csproj b/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosity.csproj new file mode 100644 index 0000000000..d8a38d749f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET DynamicViscosity</Title> + <Description>Adds DynamicViscosity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>dynamicviscosity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5dde57f4-3f98-c4b7-47e5-65229faf1f0f}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.DynamicViscosity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosity.g.cs b/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosity.g.cs new file mode 100644 index 0000000000..ec7b7cde23 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosity.g.cs @@ -0,0 +1,1030 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity + /// </remarks> + [DataContract] + public readonly partial struct DynamicViscosity : IArithmeticQuantity<DynamicViscosity, DynamicViscosityUnit, double>, IEquatable<DynamicViscosity>, IComparable, IComparable<DynamicViscosity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly DynamicViscosityUnit? _unit; + + static DynamicViscosity() + { + BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); + BaseUnit = DynamicViscosityUnit.NewtonSecondPerMeterSquared; + Units = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast<DynamicViscosityUnit>().ToArray(); + Zero = new DynamicViscosity(0, BaseUnit); + Info = new QuantityInfo<DynamicViscosityUnit>("DynamicViscosity", + new UnitInfo<DynamicViscosityUnit>[] + { + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.Centipoise, "Centipoise", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.MicropascalSecond, "MicropascalSeconds", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.MillipascalSecond, "MillipascalSeconds", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, "NewtonSecondsPerMeterSquared", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.PascalSecond, "PascalSeconds", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.Poise, "Poise", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, "PoundsForceSecondPerSquareFoot", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.PoundForceSecondPerSquareInch, "PoundsForceSecondPerSquareInch", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.PoundPerFootSecond, "PoundsPerFootSecond", BaseUnits.Undefined), + new UnitInfo<DynamicViscosityUnit>(DynamicViscosityUnit.Reyn, "Reyns", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public DynamicViscosity(double value, DynamicViscosityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="DynamicViscosity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<DynamicViscosityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. + /// </summary> + public static DynamicViscosityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the DynamicViscosity quantity. + /// </summary> + public static DynamicViscosityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. + /// </summary> + public static DynamicViscosity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static DynamicViscosity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<DynamicViscosityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.Centipoise"/> + /// </summary> + public double Centipoise => As(DynamicViscosityUnit.Centipoise); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.MicropascalSecond"/> + /// </summary> + public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.MillipascalSecond"/> + /// </summary> + public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.NewtonSecondPerMeterSquared"/> + /// </summary> + public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.PascalSecond"/> + /// </summary> + public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.Poise"/> + /// </summary> + public double Poise => As(DynamicViscosityUnit.Poise); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.PoundForceSecondPerSquareFoot"/> + /// </summary> + public double PoundsForceSecondPerSquareFoot => As(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.PoundForceSecondPerSquareInch"/> + /// </summary> + public double PoundsForceSecondPerSquareInch => As(DynamicViscosityUnit.PoundForceSecondPerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.PoundPerFootSecond"/> + /// </summary> + public double PoundsPerFootSecond => As(DynamicViscosityUnit.PoundPerFootSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="DynamicViscosityUnit.Reyn"/> + /// </summary> + public double Reyns => As(DynamicViscosityUnit.Reyn); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: DynamicViscosityUnit -> BaseUnit + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.Centipoise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.MicropascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.MillipascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.PascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.Poise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.PoundForceSecondPerSquareInch, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.PoundPerFootSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.Reyn, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity); + + // Register in unit converter: BaseUnit -> DynamicViscosityUnit + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Centipoise, quantity => quantity.ToUnit(DynamicViscosityUnit.Centipoise)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MicropascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.MicropascalSecond)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MillipascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.MillipascalSecond)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.PascalSecond)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Poise, quantity => quantity.ToUnit(DynamicViscosityUnit.Poise)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareFoot, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareFoot)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareInch, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareInch)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundPerFootSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundPerFootSecond)); + unitConverter.SetConversionFunction<DynamicViscosity>(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Reyn, quantity => quantity.ToUnit(DynamicViscosityUnit.Reyn)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.Centipoise, new CultureInfo("en-US"), false, true, new string[]{"cP"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.MicropascalSecond, new CultureInfo("en-US"), false, true, new string[]{"µPa·s", "µPaS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.MillipascalSecond, new CultureInfo("en-US"), false, true, new string[]{"mPa·s", "mPaS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.NewtonSecondPerMeterSquared, new CultureInfo("en-US"), false, true, new string[]{"Ns/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.PascalSecond, new CultureInfo("en-US"), false, true, new string[]{"Pa·s", "PaS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.Poise, new CultureInfo("en-US"), false, true, new string[]{"P"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf·s/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.PoundForceSecondPerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"lbf·s/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.PoundPerFootSecond, new CultureInfo("en-US"), false, true, new string[]{"lb/ft·s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(DynamicViscosityUnit.Reyn, new CultureInfo("en-US"), false, true, new string[]{"reyn"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(DynamicViscosityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(DynamicViscosityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.Centipoise"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromCentipoise(QuantityValue centipoise) + { + double value = (double) centipoise; + return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.MicropascalSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) + { + double value = (double) micropascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.MillipascalSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) + { + double value = (double) millipascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.NewtonSecondPerMeterSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) + { + double value = (double) newtonsecondspermetersquared; + return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.PascalSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) + { + double value = (double) pascalseconds; + return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.Poise"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromPoise(QuantityValue poise) + { + double value = (double) poise; + return new DynamicViscosity(value, DynamicViscosityUnit.Poise); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.PoundForceSecondPerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(QuantityValue poundsforcesecondpersquarefoot) + { + double value = (double) poundsforcesecondpersquarefoot; + return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.PoundForceSecondPerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromPoundsForceSecondPerSquareInch(QuantityValue poundsforcesecondpersquareinch) + { + double value = (double) poundsforcesecondpersquareinch; + return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareInch); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.PoundPerFootSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromPoundsPerFootSecond(QuantityValue poundsperfootsecond) + { + double value = (double) poundsperfootsecond; + return new DynamicViscosity(value, DynamicViscosityUnit.PoundPerFootSecond); + } + + /// <summary> + /// Creates a <see cref="DynamicViscosity"/> from <see cref="DynamicViscosityUnit.Reyn"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static DynamicViscosity FromReyns(QuantityValue reyns) + { + double value = (double) reyns; + return new DynamicViscosity(value, DynamicViscosityUnit.Reyn); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="DynamicViscosityUnit" /> to <see cref="DynamicViscosity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>DynamicViscosity unit value.</returns> + public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) + { + return new DynamicViscosity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static DynamicViscosity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static DynamicViscosity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<DynamicViscosity, DynamicViscosityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out DynamicViscosity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out DynamicViscosity result) + { + return QuantityParser.Default.TryParse<DynamicViscosity, DynamicViscosityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static DynamicViscosityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static DynamicViscosityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<DynamicViscosityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.DynamicViscosityUnit)"/> + public static bool TryParseUnit(string str, out DynamicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out DynamicViscosityUnit unit) + { + return UnitParser.Default.TryParse<DynamicViscosityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static DynamicViscosity operator -(DynamicViscosity right) + { + return new DynamicViscosity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="DynamicViscosity"/> from adding two <see cref="DynamicViscosity"/>.</summary> + public static DynamicViscosity operator +(DynamicViscosity left, DynamicViscosity right) + { + return new DynamicViscosity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="DynamicViscosity"/> from subtracting two <see cref="DynamicViscosity"/>.</summary> + public static DynamicViscosity operator -(DynamicViscosity left, DynamicViscosity right) + { + return new DynamicViscosity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="DynamicViscosity"/> from multiplying value and <see cref="DynamicViscosity"/>.</summary> + public static DynamicViscosity operator *(double left, DynamicViscosity right) + { + return new DynamicViscosity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="DynamicViscosity"/> from multiplying value and <see cref="DynamicViscosity"/>.</summary> + public static DynamicViscosity operator *(DynamicViscosity left, double right) + { + return new DynamicViscosity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="DynamicViscosity"/> from dividing <see cref="DynamicViscosity"/> by value.</summary> + public static DynamicViscosity operator /(DynamicViscosity left, double right) + { + return new DynamicViscosity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="DynamicViscosity"/> by <see cref="DynamicViscosity"/>.</summary> + public static double operator /(DynamicViscosity left, DynamicViscosity right) + { + return left.NewtonSecondsPerMeterSquared / right.NewtonSecondsPerMeterSquared; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(DynamicViscosity left, DynamicViscosity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(DynamicViscosity left, DynamicViscosity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(DynamicViscosity left, DynamicViscosity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(DynamicViscosity left, DynamicViscosity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="DynamicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(DynamicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(DynamicViscosity left, DynamicViscosity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="DynamicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(DynamicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(DynamicViscosity left, DynamicViscosity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="DynamicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(DynamicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is DynamicViscosity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="DynamicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(DynamicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(DynamicViscosity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="DynamicViscosity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is DynamicViscosity otherQuantity)) throw new ArgumentException("Expected type DynamicViscosity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="DynamicViscosity"/> with another <see cref="DynamicViscosity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(DynamicViscosity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another DynamicViscosity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current DynamicViscosity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(DynamicViscosityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is DynamicViscosityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A DynamicViscosity with the specified unit.</returns> + public DynamicViscosity ToUnit(DynamicViscosityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="DynamicViscosity"/> to another <see cref="DynamicViscosity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A DynamicViscosity with the specified unit.</returns> + public DynamicViscosity ToUnit(DynamicViscosityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(DynamicViscosity), Unit, typeof(DynamicViscosity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (DynamicViscosity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="DynamicViscosity"/> to another <see cref="DynamicViscosity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="DynamicViscosity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(DynamicViscosityUnit unit, [NotNullWhen(true)] out DynamicViscosity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + DynamicViscosity? convertedOrNull = (Unit, unit) switch + { + // DynamicViscosityUnit -> BaseUnit + (DynamicViscosityUnit.Centipoise, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity((_value / 10) * 1e-2d, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.MicropascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity((_value) * 1e-6d, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.MillipascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity((_value) * 1e-3d, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.PascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.Poise, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value / 10, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.PoundForceSecondPerSquareFoot, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 4.7880258980335843e1, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.PoundForceSecondPerSquareInch, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 6.8947572931683613e3, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.PoundPerFootSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 1.4881639, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + (DynamicViscosityUnit.Reyn, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 6.8947572931683613e3, DynamicViscosityUnit.NewtonSecondPerMeterSquared), + + // BaseUnit -> DynamicViscosityUnit + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Centipoise) => new DynamicViscosity((_value * 10) / 1e-2d, DynamicViscosityUnit.Centipoise), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MicropascalSecond) => new DynamicViscosity((_value) / 1e-6d, DynamicViscosityUnit.MicropascalSecond), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MillipascalSecond) => new DynamicViscosity((_value) / 1e-3d, DynamicViscosityUnit.MillipascalSecond), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PascalSecond) => new DynamicViscosity(_value, DynamicViscosityUnit.PascalSecond), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Poise) => new DynamicViscosity(_value * 10, DynamicViscosityUnit.Poise), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareFoot) => new DynamicViscosity(_value / 4.7880258980335843e1, DynamicViscosityUnit.PoundForceSecondPerSquareFoot), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareInch) => new DynamicViscosity(_value / 6.8947572931683613e3, DynamicViscosityUnit.PoundForceSecondPerSquareInch), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundPerFootSecond) => new DynamicViscosity(_value / 1.4881639, DynamicViscosityUnit.PoundPerFootSecond), + (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Reyn) => new DynamicViscosity(_value / 6.8947572931683613e3, DynamicViscosityUnit.Reyn), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is DynamicViscosityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<DynamicViscosityUnit> IQuantity<DynamicViscosityUnit>.ToUnit(DynamicViscosityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<DynamicViscosityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(DynamicViscosity)) + return this; + else if (conversionType == typeof(DynamicViscosityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return DynamicViscosity.Info; + else if (conversionType == typeof(BaseDimensions)) + return DynamicViscosity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosityUnit.g.cs new file mode 100644 index 0000000000..607837db48 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/DynamicViscosity/DynamicViscosityUnit.g.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum DynamicViscosityUnit + { + Centipoise = 1, + MicropascalSecond = 2, + MillipascalSecond = 3, + NewtonSecondPerMeterSquared = 4, + PascalSecond = 5, + Poise = 6, + PoundForceSecondPerSquareFoot = 7, + PoundForceSecondPerSquareInch = 8, + PoundPerFootSecond = 9, + Reyn = 10, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittance.csproj b/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittance.csproj new file mode 100644 index 0000000000..02c0024604 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricAdmittance</Title> + <Description>Adds ElectricAdmittance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricadmittance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{2ee55c63-d077-25dd-f076-857adfe08080}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricAdmittance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittance.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittance.g.cs new file mode 100644 index 0000000000..f8023181b1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittance.g.cs @@ -0,0 +1,901 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct ElectricAdmittance : IArithmeticQuantity<ElectricAdmittance, ElectricAdmittanceUnit, double>, IEquatable<ElectricAdmittance>, IComparable, IComparable<ElectricAdmittance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricAdmittanceUnit? _unit; + + static ElectricAdmittance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + BaseUnit = ElectricAdmittanceUnit.Siemens; + Units = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast<ElectricAdmittanceUnit>().ToArray(); + Zero = new ElectricAdmittance(0, BaseUnit); + Info = new QuantityInfo<ElectricAdmittanceUnit>("ElectricAdmittance", + new UnitInfo<ElectricAdmittanceUnit>[] + { + new UnitInfo<ElectricAdmittanceUnit>(ElectricAdmittanceUnit.Microsiemens, "Microsiemens", BaseUnits.Undefined), + new UnitInfo<ElectricAdmittanceUnit>(ElectricAdmittanceUnit.Millisiemens, "Millisiemens", BaseUnits.Undefined), + new UnitInfo<ElectricAdmittanceUnit>(ElectricAdmittanceUnit.Nanosiemens, "Nanosiemens", BaseUnits.Undefined), + new UnitInfo<ElectricAdmittanceUnit>(ElectricAdmittanceUnit.Siemens, "Siemens", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricAdmittance(double value, ElectricAdmittanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricAdmittance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricAdmittanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. + /// </summary> + public static ElectricAdmittanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricAdmittance quantity. + /// </summary> + public static ElectricAdmittanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// </summary> + public static ElectricAdmittance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricAdmittance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricAdmittanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricAdmittanceUnit.Microsiemens"/> + /// </summary> + public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricAdmittanceUnit.Millisiemens"/> + /// </summary> + public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricAdmittanceUnit.Nanosiemens"/> + /// </summary> + public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricAdmittanceUnit.Siemens"/> + /// </summary> + public double Siemens => As(ElectricAdmittanceUnit.Siemens); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricAdmittanceUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Microsiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Millisiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Nanosiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Siemens, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricAdmittanceUnit + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Microsiemens)); + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Millisiemens)); + unitConverter.SetConversionFunction<ElectricAdmittance>(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanosiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Nanosiemens)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricAdmittanceUnit.Microsiemens, new CultureInfo("en-US"), false, true, new string[]{"µS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricAdmittanceUnit.Millisiemens, new CultureInfo("en-US"), false, true, new string[]{"mS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricAdmittanceUnit.Nanosiemens, new CultureInfo("en-US"), false, true, new string[]{"nS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricAdmittanceUnit.Siemens, new CultureInfo("en-US"), false, true, new string[]{"S"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricAdmittanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricAdmittanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricAdmittance"/> from <see cref="ElectricAdmittanceUnit.Microsiemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) + { + double value = (double) microsiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); + } + + /// <summary> + /// Creates a <see cref="ElectricAdmittance"/> from <see cref="ElectricAdmittanceUnit.Millisiemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) + { + double value = (double) millisiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); + } + + /// <summary> + /// Creates a <see cref="ElectricAdmittance"/> from <see cref="ElectricAdmittanceUnit.Nanosiemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) + { + double value = (double) nanosiemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); + } + + /// <summary> + /// Creates a <see cref="ElectricAdmittance"/> from <see cref="ElectricAdmittanceUnit.Siemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricAdmittance FromSiemens(QuantityValue siemens) + { + double value = (double) siemens; + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricAdmittanceUnit" /> to <see cref="ElectricAdmittance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricAdmittance unit value.</returns> + public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) + { + return new ElectricAdmittance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricAdmittance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricAdmittance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricAdmittance, ElectricAdmittanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricAdmittance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricAdmittance result) + { + return QuantityParser.Default.TryParse<ElectricAdmittance, ElectricAdmittanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricAdmittanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricAdmittanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricAdmittanceUnit)"/> + public static bool TryParseUnit(string str, out ElectricAdmittanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricAdmittanceUnit unit) + { + return UnitParser.Default.TryParse<ElectricAdmittanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricAdmittance operator -(ElectricAdmittance right) + { + return new ElectricAdmittance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricAdmittance"/> from adding two <see cref="ElectricAdmittance"/>.</summary> + public static ElectricAdmittance operator +(ElectricAdmittance left, ElectricAdmittance right) + { + return new ElectricAdmittance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricAdmittance"/> from subtracting two <see cref="ElectricAdmittance"/>.</summary> + public static ElectricAdmittance operator -(ElectricAdmittance left, ElectricAdmittance right) + { + return new ElectricAdmittance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricAdmittance"/> from multiplying value and <see cref="ElectricAdmittance"/>.</summary> + public static ElectricAdmittance operator *(double left, ElectricAdmittance right) + { + return new ElectricAdmittance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricAdmittance"/> from multiplying value and <see cref="ElectricAdmittance"/>.</summary> + public static ElectricAdmittance operator *(ElectricAdmittance left, double right) + { + return new ElectricAdmittance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricAdmittance"/> from dividing <see cref="ElectricAdmittance"/> by value.</summary> + public static ElectricAdmittance operator /(ElectricAdmittance left, double right) + { + return new ElectricAdmittance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricAdmittance"/> by <see cref="ElectricAdmittance"/>.</summary> + public static double operator /(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Siemens / right.Siemens; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricAdmittance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricAdmittance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricAdmittance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricAdmittance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricAdmittance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricAdmittance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricAdmittance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricAdmittance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricAdmittance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricAdmittance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricAdmittance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricAdmittance otherQuantity)) throw new ArgumentException("Expected type ElectricAdmittance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricAdmittance"/> with another <see cref="ElectricAdmittance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricAdmittance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricAdmittance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricAdmittance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricAdmittanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricAdmittanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricAdmittance with the specified unit.</returns> + public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricAdmittance"/> to another <see cref="ElectricAdmittance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricAdmittance with the specified unit.</returns> + public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricAdmittance), Unit, typeof(ElectricAdmittance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricAdmittance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricAdmittance"/> to another <see cref="ElectricAdmittance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricAdmittance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricAdmittanceUnit unit, [NotNullWhen(true)] out ElectricAdmittance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricAdmittance? convertedOrNull = (Unit, unit) switch + { + // ElectricAdmittanceUnit -> BaseUnit + (ElectricAdmittanceUnit.Microsiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-6d, ElectricAdmittanceUnit.Siemens), + (ElectricAdmittanceUnit.Millisiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-3d, ElectricAdmittanceUnit.Siemens), + (ElectricAdmittanceUnit.Nanosiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-9d, ElectricAdmittanceUnit.Siemens), + + // BaseUnit -> ElectricAdmittanceUnit + (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Microsiemens) => new ElectricAdmittance((_value) / 1e-6d, ElectricAdmittanceUnit.Microsiemens), + (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millisiemens) => new ElectricAdmittance((_value) / 1e-3d, ElectricAdmittanceUnit.Millisiemens), + (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanosiemens) => new ElectricAdmittance((_value) / 1e-9d, ElectricAdmittanceUnit.Nanosiemens), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricAdmittanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricAdmittanceUnit> IQuantity<ElectricAdmittanceUnit>.ToUnit(ElectricAdmittanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricAdmittanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricAdmittance)) + return this; + else if (conversionType == typeof(ElectricAdmittanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricAdmittance.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricAdmittance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittanceUnit.g.cs new file mode 100644 index 0000000000..622b45de43 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricAdmittance/ElectricAdmittanceUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricAdmittanceUnit + { + Microsiemens = 1, + Millisiemens = 2, + Nanosiemens = 3, + Siemens = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricCharge.csproj b/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricCharge.csproj new file mode 100644 index 0000000000..80979d8c77 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricCharge.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricCharge</Title> + <Description>Adds ElectricCharge units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electriccharge unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f4286cfc-484b-8466-8efa-1111696babb9}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricCharge</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricCharge.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricCharge.g.cs new file mode 100644 index 0000000000..0a626c0518 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricCharge.g.cs @@ -0,0 +1,925 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Electric_charge + /// </remarks> + [DataContract] + public readonly partial struct ElectricCharge : IArithmeticQuantity<ElectricCharge, ElectricChargeUnit, double>, IEquatable<ElectricCharge>, IComparable, IComparable<ElectricCharge>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricChargeUnit? _unit; + + static ElectricCharge() + { + BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); + BaseUnit = ElectricChargeUnit.Coulomb; + Units = Enum.GetValues(typeof(ElectricChargeUnit)).Cast<ElectricChargeUnit>().ToArray(); + Zero = new ElectricCharge(0, BaseUnit); + Info = new QuantityInfo<ElectricChargeUnit>("ElectricCharge", + new UnitInfo<ElectricChargeUnit>[] + { + new UnitInfo<ElectricChargeUnit>(ElectricChargeUnit.AmpereHour, "AmpereHours", BaseUnits.Undefined), + new UnitInfo<ElectricChargeUnit>(ElectricChargeUnit.Coulomb, "Coulombs", BaseUnits.Undefined), + new UnitInfo<ElectricChargeUnit>(ElectricChargeUnit.KiloampereHour, "KiloampereHours", BaseUnits.Undefined), + new UnitInfo<ElectricChargeUnit>(ElectricChargeUnit.MegaampereHour, "MegaampereHours", BaseUnits.Undefined), + new UnitInfo<ElectricChargeUnit>(ElectricChargeUnit.MilliampereHour, "MilliampereHours", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricCharge(double value, ElectricChargeUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricCharge" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricChargeUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. + /// </summary> + public static ElectricChargeUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricCharge quantity. + /// </summary> + public static ElectricChargeUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. + /// </summary> + public static ElectricCharge Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricCharge AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricChargeUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricChargeUnit.AmpereHour"/> + /// </summary> + public double AmpereHours => As(ElectricChargeUnit.AmpereHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricChargeUnit.Coulomb"/> + /// </summary> + public double Coulombs => As(ElectricChargeUnit.Coulomb); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricChargeUnit.KiloampereHour"/> + /// </summary> + public double KiloampereHours => As(ElectricChargeUnit.KiloampereHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricChargeUnit.MegaampereHour"/> + /// </summary> + public double MegaampereHours => As(ElectricChargeUnit.MegaampereHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricChargeUnit.MilliampereHour"/> + /// </summary> + public double MilliampereHours => As(ElectricChargeUnit.MilliampereHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricChargeUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.AmpereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.KiloampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.MegaampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.MilliampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Coulomb, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricChargeUnit + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.Coulomb, ElectricChargeUnit.AmpereHour, quantity => quantity.ToUnit(ElectricChargeUnit.AmpereHour)); + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.Coulomb, ElectricChargeUnit.KiloampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.KiloampereHour)); + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MegaampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.MegaampereHour)); + unitConverter.SetConversionFunction<ElectricCharge>(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MilliampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.MilliampereHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeUnit.AmpereHour, new CultureInfo("en-US"), false, true, new string[]{"A-h", "Ah"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeUnit.Coulomb, new CultureInfo("en-US"), false, true, new string[]{"C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeUnit.KiloampereHour, new CultureInfo("en-US"), false, true, new string[]{"kA-h", "kAh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeUnit.MegaampereHour, new CultureInfo("en-US"), false, true, new string[]{"MA-h", "MAh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeUnit.MilliampereHour, new CultureInfo("en-US"), false, true, new string[]{"mA-h", "mAh"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricChargeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricChargeUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricCharge"/> from <see cref="ElectricChargeUnit.AmpereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCharge FromAmpereHours(QuantityValue amperehours) + { + double value = (double) amperehours; + return new ElectricCharge(value, ElectricChargeUnit.AmpereHour); + } + + /// <summary> + /// Creates a <see cref="ElectricCharge"/> from <see cref="ElectricChargeUnit.Coulomb"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCharge FromCoulombs(QuantityValue coulombs) + { + double value = (double) coulombs; + return new ElectricCharge(value, ElectricChargeUnit.Coulomb); + } + + /// <summary> + /// Creates a <see cref="ElectricCharge"/> from <see cref="ElectricChargeUnit.KiloampereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCharge FromKiloampereHours(QuantityValue kiloamperehours) + { + double value = (double) kiloamperehours; + return new ElectricCharge(value, ElectricChargeUnit.KiloampereHour); + } + + /// <summary> + /// Creates a <see cref="ElectricCharge"/> from <see cref="ElectricChargeUnit.MegaampereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCharge FromMegaampereHours(QuantityValue megaamperehours) + { + double value = (double) megaamperehours; + return new ElectricCharge(value, ElectricChargeUnit.MegaampereHour); + } + + /// <summary> + /// Creates a <see cref="ElectricCharge"/> from <see cref="ElectricChargeUnit.MilliampereHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCharge FromMilliampereHours(QuantityValue milliamperehours) + { + double value = (double) milliamperehours; + return new ElectricCharge(value, ElectricChargeUnit.MilliampereHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricChargeUnit" /> to <see cref="ElectricCharge" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricCharge unit value.</returns> + public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) + { + return new ElectricCharge((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricCharge Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricCharge Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricCharge, ElectricChargeUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricCharge result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCharge result) + { + return QuantityParser.Default.TryParse<ElectricCharge, ElectricChargeUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricChargeUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricChargeUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricChargeUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricChargeUnit)"/> + public static bool TryParseUnit(string str, out ElectricChargeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricChargeUnit unit) + { + return UnitParser.Default.TryParse<ElectricChargeUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricCharge operator -(ElectricCharge right) + { + return new ElectricCharge(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCharge"/> from adding two <see cref="ElectricCharge"/>.</summary> + public static ElectricCharge operator +(ElectricCharge left, ElectricCharge right) + { + return new ElectricCharge(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCharge"/> from subtracting two <see cref="ElectricCharge"/>.</summary> + public static ElectricCharge operator -(ElectricCharge left, ElectricCharge right) + { + return new ElectricCharge(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCharge"/> from multiplying value and <see cref="ElectricCharge"/>.</summary> + public static ElectricCharge operator *(double left, ElectricCharge right) + { + return new ElectricCharge(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCharge"/> from multiplying value and <see cref="ElectricCharge"/>.</summary> + public static ElectricCharge operator *(ElectricCharge left, double right) + { + return new ElectricCharge(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricCharge"/> from dividing <see cref="ElectricCharge"/> by value.</summary> + public static ElectricCharge operator /(ElectricCharge left, double right) + { + return new ElectricCharge(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricCharge"/> by <see cref="ElectricCharge"/>.</summary> + public static double operator /(ElectricCharge left, ElectricCharge right) + { + return left.Coulombs / right.Coulombs; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricCharge left, ElectricCharge right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricCharge left, ElectricCharge right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricCharge left, ElectricCharge right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricCharge left, ElectricCharge right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricCharge"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCharge, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricCharge left, ElectricCharge right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricCharge"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCharge, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricCharge left, ElectricCharge right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCharge"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCharge, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricCharge otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCharge"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCharge, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricCharge other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricCharge"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricCharge otherQuantity)) throw new ArgumentException("Expected type ElectricCharge.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricCharge"/> with another <see cref="ElectricCharge"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricCharge other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricCharge within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricCharge.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricChargeUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricChargeUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricCharge to another ElectricCharge with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricCharge with the specified unit.</returns> + public ElectricCharge ToUnit(ElectricChargeUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricCharge"/> to another <see cref="ElectricCharge"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricCharge with the specified unit.</returns> + public ElectricCharge ToUnit(ElectricChargeUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricCharge), Unit, typeof(ElectricCharge), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricCharge)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricCharge"/> to another <see cref="ElectricCharge"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricCharge"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricChargeUnit unit, [NotNullWhen(true)] out ElectricCharge? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricCharge? convertedOrNull = (Unit, unit) switch + { + // ElectricChargeUnit -> BaseUnit + (ElectricChargeUnit.AmpereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge(_value / 2.77777777777e-4, ElectricChargeUnit.Coulomb), + (ElectricChargeUnit.KiloampereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value / 2.77777777777e-4) * 1e3d, ElectricChargeUnit.Coulomb), + (ElectricChargeUnit.MegaampereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value / 2.77777777777e-4) * 1e6d, ElectricChargeUnit.Coulomb), + (ElectricChargeUnit.MilliampereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value / 2.77777777777e-4) * 1e-3d, ElectricChargeUnit.Coulomb), + + // BaseUnit -> ElectricChargeUnit + (ElectricChargeUnit.Coulomb, ElectricChargeUnit.AmpereHour) => new ElectricCharge(_value * 2.77777777777e-4, ElectricChargeUnit.AmpereHour), + (ElectricChargeUnit.Coulomb, ElectricChargeUnit.KiloampereHour) => new ElectricCharge((_value * 2.77777777777e-4) / 1e3d, ElectricChargeUnit.KiloampereHour), + (ElectricChargeUnit.Coulomb, ElectricChargeUnit.MegaampereHour) => new ElectricCharge((_value * 2.77777777777e-4) / 1e6d, ElectricChargeUnit.MegaampereHour), + (ElectricChargeUnit.Coulomb, ElectricChargeUnit.MilliampereHour) => new ElectricCharge((_value * 2.77777777777e-4) / 1e-3d, ElectricChargeUnit.MilliampereHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricChargeUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricChargeUnit> IQuantity<ElectricChargeUnit>.ToUnit(ElectricChargeUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricChargeUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricCharge)) + return this; + else if (conversionType == typeof(ElectricChargeUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricCharge.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricCharge.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricChargeUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricChargeUnit.g.cs new file mode 100644 index 0000000000..4fda90bf6f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCharge/ElectricChargeUnit.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricChargeUnit + { + AmpereHour = 1, + Coulomb = 2, + KiloampereHour = 3, + MegaampereHour = 4, + MilliampereHour = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensity.csproj b/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensity.csproj new file mode 100644 index 0000000000..13ad15dd5a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricChargeDensity</Title> + <Description>Adds ElectricChargeDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricchargedensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{b1567c85-ad77-c283-9165-777ad0e9a2eb}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricChargeDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensity.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensity.g.cs new file mode 100644 index 0000000000..0f545827b7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensity.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In electromagnetism, charge density is a measure of the amount of electric charge per volume. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Charge_density + /// </remarks> + [DataContract] + public readonly partial struct ElectricChargeDensity : IArithmeticQuantity<ElectricChargeDensity, ElectricChargeDensityUnit, double>, IEquatable<ElectricChargeDensity>, IComparable, IComparable<ElectricChargeDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricChargeDensityUnit? _unit; + + static ElectricChargeDensity() + { + BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); + BaseUnit = ElectricChargeDensityUnit.CoulombPerCubicMeter; + Units = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast<ElectricChargeDensityUnit>().ToArray(); + Zero = new ElectricChargeDensity(0, BaseUnit); + Info = new QuantityInfo<ElectricChargeDensityUnit>("ElectricChargeDensity", + new UnitInfo<ElectricChargeDensityUnit>[] + { + new UnitInfo<ElectricChargeDensityUnit>(ElectricChargeDensityUnit.CoulombPerCubicMeter, "CoulombsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricChargeDensity(double value, ElectricChargeDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricChargeDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricChargeDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. + /// </summary> + public static ElectricChargeDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricChargeDensity quantity. + /// </summary> + public static ElectricChargeDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. + /// </summary> + public static ElectricChargeDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricChargeDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricChargeDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricChargeDensityUnit.CoulombPerCubicMeter"/> + /// </summary> + public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricChargeDensityUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricChargeDensity>(ElectricChargeDensityUnit.CoulombPerCubicMeter, ElectricChargeDensityUnit.CoulombPerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricChargeDensityUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricChargeDensityUnit.CoulombPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"C/m³"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricChargeDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricChargeDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricChargeDensity"/> from <see cref="ElectricChargeDensityUnit.CoulombPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) + { + double value = (double) coulombspercubicmeter; + return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricChargeDensityUnit" /> to <see cref="ElectricChargeDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricChargeDensity unit value.</returns> + public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) + { + return new ElectricChargeDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricChargeDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricChargeDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricChargeDensity, ElectricChargeDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricChargeDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricChargeDensity result) + { + return QuantityParser.Default.TryParse<ElectricChargeDensity, ElectricChargeDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricChargeDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricChargeDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricChargeDensityUnit)"/> + public static bool TryParseUnit(string str, out ElectricChargeDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricChargeDensityUnit unit) + { + return UnitParser.Default.TryParse<ElectricChargeDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricChargeDensity operator -(ElectricChargeDensity right) + { + return new ElectricChargeDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricChargeDensity"/> from adding two <see cref="ElectricChargeDensity"/>.</summary> + public static ElectricChargeDensity operator +(ElectricChargeDensity left, ElectricChargeDensity right) + { + return new ElectricChargeDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricChargeDensity"/> from subtracting two <see cref="ElectricChargeDensity"/>.</summary> + public static ElectricChargeDensity operator -(ElectricChargeDensity left, ElectricChargeDensity right) + { + return new ElectricChargeDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricChargeDensity"/> from multiplying value and <see cref="ElectricChargeDensity"/>.</summary> + public static ElectricChargeDensity operator *(double left, ElectricChargeDensity right) + { + return new ElectricChargeDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricChargeDensity"/> from multiplying value and <see cref="ElectricChargeDensity"/>.</summary> + public static ElectricChargeDensity operator *(ElectricChargeDensity left, double right) + { + return new ElectricChargeDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricChargeDensity"/> from dividing <see cref="ElectricChargeDensity"/> by value.</summary> + public static ElectricChargeDensity operator /(ElectricChargeDensity left, double right) + { + return new ElectricChargeDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricChargeDensity"/> by <see cref="ElectricChargeDensity"/>.</summary> + public static double operator /(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.CoulombsPerCubicMeter / right.CoulombsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricChargeDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricChargeDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricChargeDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricChargeDensity otherQuantity)) throw new ArgumentException("Expected type ElectricChargeDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricChargeDensity"/> with another <see cref="ElectricChargeDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricChargeDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricChargeDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricChargeDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricChargeDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricChargeDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricChargeDensity with the specified unit.</returns> + public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricChargeDensity"/> to another <see cref="ElectricChargeDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricChargeDensity with the specified unit.</returns> + public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricChargeDensity), Unit, typeof(ElectricChargeDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricChargeDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricChargeDensity"/> to another <see cref="ElectricChargeDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricChargeDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricChargeDensityUnit unit, [NotNullWhen(true)] out ElectricChargeDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricChargeDensity? convertedOrNull = (Unit, unit) switch + { + // ElectricChargeDensityUnit -> BaseUnit + + // BaseUnit -> ElectricChargeDensityUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricChargeDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricChargeDensityUnit> IQuantity<ElectricChargeDensityUnit>.ToUnit(ElectricChargeDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricChargeDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricChargeDensity)) + return this; + else if (conversionType == typeof(ElectricChargeDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricChargeDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricChargeDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensityUnit.g.cs new file mode 100644 index 0000000000..05909c9a62 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricChargeDensity/ElectricChargeDensityUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricChargeDensityUnit + { + CoulombPerCubicMeter = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductance.csproj b/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductance.csproj new file mode 100644 index 0000000000..fb374a8dd6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricConductance</Title> + <Description>Adds ElectricConductance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricconductance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{fcd3dfb2-9ee2-ad22-0e1f-4cddd575792a}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricConductance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductance.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductance.g.cs new file mode 100644 index 0000000000..8857d13cd8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductance.g.cs @@ -0,0 +1,883 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance + /// </remarks> + [DataContract] + public readonly partial struct ElectricConductance : IArithmeticQuantity<ElectricConductance, ElectricConductanceUnit, double>, IEquatable<ElectricConductance>, IComparable, IComparable<ElectricConductance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricConductanceUnit? _unit; + + static ElectricConductance() + { + BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + BaseUnit = ElectricConductanceUnit.Siemens; + Units = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast<ElectricConductanceUnit>().ToArray(); + Zero = new ElectricConductance(0, BaseUnit); + Info = new QuantityInfo<ElectricConductanceUnit>("ElectricConductance", + new UnitInfo<ElectricConductanceUnit>[] + { + new UnitInfo<ElectricConductanceUnit>(ElectricConductanceUnit.Microsiemens, "Microsiemens", BaseUnits.Undefined), + new UnitInfo<ElectricConductanceUnit>(ElectricConductanceUnit.Millisiemens, "Millisiemens", BaseUnits.Undefined), + new UnitInfo<ElectricConductanceUnit>(ElectricConductanceUnit.Siemens, "Siemens", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricConductance(double value, ElectricConductanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricConductance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricConductanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. + /// </summary> + public static ElectricConductanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricConductance quantity. + /// </summary> + public static ElectricConductanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. + /// </summary> + public static ElectricConductance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricConductance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricConductanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductanceUnit.Microsiemens"/> + /// </summary> + public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductanceUnit.Millisiemens"/> + /// </summary> + public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductanceUnit.Siemens"/> + /// </summary> + public double Siemens => As(ElectricConductanceUnit.Siemens); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricConductanceUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricConductance>(ElectricConductanceUnit.Microsiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); + unitConverter.SetConversionFunction<ElectricConductance>(ElectricConductanceUnit.Millisiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricConductance>(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Siemens, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricConductanceUnit + unitConverter.SetConversionFunction<ElectricConductance>(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Microsiemens)); + unitConverter.SetConversionFunction<ElectricConductance>(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Millisiemens)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductanceUnit.Microsiemens, new CultureInfo("en-US"), false, true, new string[]{"µS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductanceUnit.Millisiemens, new CultureInfo("en-US"), false, true, new string[]{"mS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductanceUnit.Siemens, new CultureInfo("en-US"), false, true, new string[]{"S"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricConductanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricConductanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricConductance"/> from <see cref="ElectricConductanceUnit.Microsiemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) + { + double value = (double) microsiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); + } + + /// <summary> + /// Creates a <see cref="ElectricConductance"/> from <see cref="ElectricConductanceUnit.Millisiemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) + { + double value = (double) millisiemens; + return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); + } + + /// <summary> + /// Creates a <see cref="ElectricConductance"/> from <see cref="ElectricConductanceUnit.Siemens"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductance FromSiemens(QuantityValue siemens) + { + double value = (double) siemens; + return new ElectricConductance(value, ElectricConductanceUnit.Siemens); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricConductanceUnit" /> to <see cref="ElectricConductance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricConductance unit value.</returns> + public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) + { + return new ElectricConductance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricConductance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricConductance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricConductance, ElectricConductanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricConductance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricConductance result) + { + return QuantityParser.Default.TryParse<ElectricConductance, ElectricConductanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricConductanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricConductanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricConductanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricConductanceUnit)"/> + public static bool TryParseUnit(string str, out ElectricConductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricConductanceUnit unit) + { + return UnitParser.Default.TryParse<ElectricConductanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricConductance operator -(ElectricConductance right) + { + return new ElectricConductance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricConductance"/> from adding two <see cref="ElectricConductance"/>.</summary> + public static ElectricConductance operator +(ElectricConductance left, ElectricConductance right) + { + return new ElectricConductance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricConductance"/> from subtracting two <see cref="ElectricConductance"/>.</summary> + public static ElectricConductance operator -(ElectricConductance left, ElectricConductance right) + { + return new ElectricConductance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricConductance"/> from multiplying value and <see cref="ElectricConductance"/>.</summary> + public static ElectricConductance operator *(double left, ElectricConductance right) + { + return new ElectricConductance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricConductance"/> from multiplying value and <see cref="ElectricConductance"/>.</summary> + public static ElectricConductance operator *(ElectricConductance left, double right) + { + return new ElectricConductance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricConductance"/> from dividing <see cref="ElectricConductance"/> by value.</summary> + public static ElectricConductance operator /(ElectricConductance left, double right) + { + return new ElectricConductance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricConductance"/> by <see cref="ElectricConductance"/>.</summary> + public static double operator /(ElectricConductance left, ElectricConductance right) + { + return left.Siemens / right.Siemens; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricConductance left, ElectricConductance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricConductance left, ElectricConductance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricConductance left, ElectricConductance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricConductance left, ElectricConductance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricConductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricConductance left, ElectricConductance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricConductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricConductance left, ElectricConductance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricConductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricConductance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricConductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricConductance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricConductance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricConductance otherQuantity)) throw new ArgumentException("Expected type ElectricConductance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricConductance"/> with another <see cref="ElectricConductance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricConductance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricConductance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricConductance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricConductanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricConductanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricConductance to another ElectricConductance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricConductance with the specified unit.</returns> + public ElectricConductance ToUnit(ElectricConductanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricConductance"/> to another <see cref="ElectricConductance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricConductance with the specified unit.</returns> + public ElectricConductance ToUnit(ElectricConductanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricConductance), Unit, typeof(ElectricConductance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricConductance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricConductance"/> to another <see cref="ElectricConductance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricConductance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricConductanceUnit unit, [NotNullWhen(true)] out ElectricConductance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricConductance? convertedOrNull = (Unit, unit) switch + { + // ElectricConductanceUnit -> BaseUnit + (ElectricConductanceUnit.Microsiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-6d, ElectricConductanceUnit.Siemens), + (ElectricConductanceUnit.Millisiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-3d, ElectricConductanceUnit.Siemens), + + // BaseUnit -> ElectricConductanceUnit + (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Microsiemens) => new ElectricConductance((_value) / 1e-6d, ElectricConductanceUnit.Microsiemens), + (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millisiemens) => new ElectricConductance((_value) / 1e-3d, ElectricConductanceUnit.Millisiemens), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricConductanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricConductanceUnit> IQuantity<ElectricConductanceUnit>.ToUnit(ElectricConductanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricConductanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricConductance)) + return this; + else if (conversionType == typeof(ElectricConductanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricConductance.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricConductance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductanceUnit.g.cs new file mode 100644 index 0000000000..7bd2b92711 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricConductance/ElectricConductanceUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricConductanceUnit + { + Microsiemens = 1, + Millisiemens = 2, + Siemens = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivity.csproj b/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivity.csproj new file mode 100644 index 0000000000..785aabb0be --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricConductivity</Title> + <Description>Adds ElectricConductivity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricconductivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f420eccc-b12d-72e4-2ad2-f93054eeec30}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricConductivity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivity.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivity.g.cs new file mode 100644 index 0000000000..22ea2f84ee --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivity.g.cs @@ -0,0 +1,946 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// </remarks> + [DataContract] + public readonly partial struct ElectricConductivity : IArithmeticQuantity<ElectricConductivity, ElectricConductivityUnit, double>, IEquatable<ElectricConductivity>, IComparable, IComparable<ElectricConductivity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricConductivityUnit? _unit; + + static ElectricConductivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); + BaseUnit = ElectricConductivityUnit.SiemensPerMeter; + Units = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast<ElectricConductivityUnit>().ToArray(); + Zero = new ElectricConductivity(0, BaseUnit); + Info = new QuantityInfo<ElectricConductivityUnit>("ElectricConductivity", + new UnitInfo<ElectricConductivityUnit>[] + { + new UnitInfo<ElectricConductivityUnit>(ElectricConductivityUnit.MicrosiemensPerCentimeter, "MicrosiemensPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricConductivityUnit>(ElectricConductivityUnit.MillisiemensPerCentimeter, "MillisiemensPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricConductivityUnit>(ElectricConductivityUnit.SiemensPerCentimeter, "SiemensPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricConductivityUnit>(ElectricConductivityUnit.SiemensPerFoot, "SiemensPerFoot", BaseUnits.Undefined), + new UnitInfo<ElectricConductivityUnit>(ElectricConductivityUnit.SiemensPerInch, "SiemensPerInch", BaseUnits.Undefined), + new UnitInfo<ElectricConductivityUnit>(ElectricConductivityUnit.SiemensPerMeter, "SiemensPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricConductivity(double value, ElectricConductivityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricConductivity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricConductivityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. + /// </summary> + public static ElectricConductivityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricConductivity quantity. + /// </summary> + public static ElectricConductivityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. + /// </summary> + public static ElectricConductivity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricConductivity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricConductivityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductivityUnit.MicrosiemensPerCentimeter"/> + /// </summary> + public double MicrosiemensPerCentimeter => As(ElectricConductivityUnit.MicrosiemensPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductivityUnit.MillisiemensPerCentimeter"/> + /// </summary> + public double MillisiemensPerCentimeter => As(ElectricConductivityUnit.MillisiemensPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductivityUnit.SiemensPerCentimeter"/> + /// </summary> + public double SiemensPerCentimeter => As(ElectricConductivityUnit.SiemensPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductivityUnit.SiemensPerFoot"/> + /// </summary> + public double SiemensPerFoot => As(ElectricConductivityUnit.SiemensPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductivityUnit.SiemensPerInch"/> + /// </summary> + public double SiemensPerInch => As(ElectricConductivityUnit.SiemensPerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricConductivityUnit.SiemensPerMeter"/> + /// </summary> + public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricConductivityUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.MicrosiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.MillisiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerFoot, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerInch, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricConductivityUnit + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MicrosiemensPerCentimeter, quantity => quantity.ToUnit(ElectricConductivityUnit.MicrosiemensPerCentimeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MillisiemensPerCentimeter, quantity => quantity.ToUnit(ElectricConductivityUnit.MillisiemensPerCentimeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerCentimeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerCentimeter)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerFoot, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerFoot)); + unitConverter.SetConversionFunction<ElectricConductivity>(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerInch, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerInch)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductivityUnit.MicrosiemensPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"µS/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductivityUnit.MillisiemensPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mS/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductivityUnit.SiemensPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"S/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductivityUnit.SiemensPerFoot, new CultureInfo("en-US"), false, true, new string[]{"S/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductivityUnit.SiemensPerInch, new CultureInfo("en-US"), false, true, new string[]{"S/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricConductivityUnit.SiemensPerMeter, new CultureInfo("en-US"), false, true, new string[]{"S/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricConductivityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricConductivity"/> from <see cref="ElectricConductivityUnit.MicrosiemensPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductivity FromMicrosiemensPerCentimeter(QuantityValue microsiemenspercentimeter) + { + double value = (double) microsiemenspercentimeter; + return new ElectricConductivity(value, ElectricConductivityUnit.MicrosiemensPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricConductivity"/> from <see cref="ElectricConductivityUnit.MillisiemensPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductivity FromMillisiemensPerCentimeter(QuantityValue millisiemenspercentimeter) + { + double value = (double) millisiemenspercentimeter; + return new ElectricConductivity(value, ElectricConductivityUnit.MillisiemensPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricConductivity"/> from <see cref="ElectricConductivityUnit.SiemensPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductivity FromSiemensPerCentimeter(QuantityValue siemenspercentimeter) + { + double value = (double) siemenspercentimeter; + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricConductivity"/> from <see cref="ElectricConductivityUnit.SiemensPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductivity FromSiemensPerFoot(QuantityValue siemensperfoot) + { + double value = (double) siemensperfoot; + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerFoot); + } + + /// <summary> + /// Creates a <see cref="ElectricConductivity"/> from <see cref="ElectricConductivityUnit.SiemensPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductivity FromSiemensPerInch(QuantityValue siemensperinch) + { + double value = (double) siemensperinch; + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerInch); + } + + /// <summary> + /// Creates a <see cref="ElectricConductivity"/> from <see cref="ElectricConductivityUnit.SiemensPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) + { + double value = (double) siemenspermeter; + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricConductivityUnit" /> to <see cref="ElectricConductivity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricConductivity unit value.</returns> + public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) + { + return new ElectricConductivity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricConductivity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricConductivity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricConductivity, ElectricConductivityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricConductivity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricConductivity result) + { + return QuantityParser.Default.TryParse<ElectricConductivity, ElectricConductivityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricConductivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricConductivityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricConductivityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricConductivityUnit)"/> + public static bool TryParseUnit(string str, out ElectricConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricConductivityUnit unit) + { + return UnitParser.Default.TryParse<ElectricConductivityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricConductivity operator -(ElectricConductivity right) + { + return new ElectricConductivity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricConductivity"/> from adding two <see cref="ElectricConductivity"/>.</summary> + public static ElectricConductivity operator +(ElectricConductivity left, ElectricConductivity right) + { + return new ElectricConductivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricConductivity"/> from subtracting two <see cref="ElectricConductivity"/>.</summary> + public static ElectricConductivity operator -(ElectricConductivity left, ElectricConductivity right) + { + return new ElectricConductivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricConductivity"/> from multiplying value and <see cref="ElectricConductivity"/>.</summary> + public static ElectricConductivity operator *(double left, ElectricConductivity right) + { + return new ElectricConductivity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricConductivity"/> from multiplying value and <see cref="ElectricConductivity"/>.</summary> + public static ElectricConductivity operator *(ElectricConductivity left, double right) + { + return new ElectricConductivity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricConductivity"/> from dividing <see cref="ElectricConductivity"/> by value.</summary> + public static ElectricConductivity operator /(ElectricConductivity left, double right) + { + return new ElectricConductivity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricConductivity"/> by <see cref="ElectricConductivity"/>.</summary> + public static double operator /(ElectricConductivity left, ElectricConductivity right) + { + return left.SiemensPerMeter / right.SiemensPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricConductivity left, ElectricConductivity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricConductivity left, ElectricConductivity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricConductivity left, ElectricConductivity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricConductivity left, ElectricConductivity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricConductivity left, ElectricConductivity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricConductivity left, ElectricConductivity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricConductivity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricConductivity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricConductivity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricConductivity otherQuantity)) throw new ArgumentException("Expected type ElectricConductivity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricConductivity"/> with another <see cref="ElectricConductivity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricConductivity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricConductivity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricConductivity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricConductivityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricConductivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricConductivity with the specified unit.</returns> + public ElectricConductivity ToUnit(ElectricConductivityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricConductivity"/> to another <see cref="ElectricConductivity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricConductivity with the specified unit.</returns> + public ElectricConductivity ToUnit(ElectricConductivityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricConductivity), Unit, typeof(ElectricConductivity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricConductivity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricConductivity"/> to another <see cref="ElectricConductivity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricConductivity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricConductivityUnit unit, [NotNullWhen(true)] out ElectricConductivity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricConductivity? convertedOrNull = (Unit, unit) switch + { + // ElectricConductivityUnit -> BaseUnit + (ElectricConductivityUnit.MicrosiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity((_value * 1e2) * 1e-6d, ElectricConductivityUnit.SiemensPerMeter), + (ElectricConductivityUnit.MillisiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity((_value * 1e2) * 1e-3d, ElectricConductivityUnit.SiemensPerMeter), + (ElectricConductivityUnit.SiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity(_value * 1e2, ElectricConductivityUnit.SiemensPerMeter), + (ElectricConductivityUnit.SiemensPerFoot, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity(_value * 3.2808398950131234, ElectricConductivityUnit.SiemensPerMeter), + (ElectricConductivityUnit.SiemensPerInch, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity(_value * 3.937007874015748e1, ElectricConductivityUnit.SiemensPerMeter), + + // BaseUnit -> ElectricConductivityUnit + (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MicrosiemensPerCentimeter) => new ElectricConductivity((_value / 1e2) / 1e-6d, ElectricConductivityUnit.MicrosiemensPerCentimeter), + (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MillisiemensPerCentimeter) => new ElectricConductivity((_value / 1e2) / 1e-3d, ElectricConductivityUnit.MillisiemensPerCentimeter), + (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerCentimeter) => new ElectricConductivity(_value / 1e2, ElectricConductivityUnit.SiemensPerCentimeter), + (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerFoot) => new ElectricConductivity(_value / 3.2808398950131234, ElectricConductivityUnit.SiemensPerFoot), + (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerInch) => new ElectricConductivity(_value / 3.937007874015748e1, ElectricConductivityUnit.SiemensPerInch), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricConductivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricConductivityUnit> IQuantity<ElectricConductivityUnit>.ToUnit(ElectricConductivityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricConductivityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricConductivity)) + return this; + else if (conversionType == typeof(ElectricConductivityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricConductivity.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricConductivity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivityUnit.g.cs new file mode 100644 index 0000000000..3bca9b88e6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricConductivity/ElectricConductivityUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricConductivityUnit + { + MicrosiemensPerCentimeter = 6, + MillisiemensPerCentimeter = 12, + SiemensPerCentimeter = 13, + SiemensPerFoot = 1, + SiemensPerInch = 2, + SiemensPerMeter = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrent.csproj b/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrent.csproj new file mode 100644 index 0000000000..b0bf1ecd40 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrent.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricCurrent</Title> + <Description>Adds ElectricCurrent units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electriccurrent unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{55160a70-69b2-4144-b974-b64d78bd50e0}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricCurrent</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrent.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrent.g.cs new file mode 100644 index 0000000000..cab350c564 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrent.g.cs @@ -0,0 +1,985 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct ElectricCurrent : IArithmeticQuantity<ElectricCurrent, ElectricCurrentUnit, double>, IEquatable<ElectricCurrent>, IComparable, IComparable<ElectricCurrent>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricCurrentUnit? _unit; + + static ElectricCurrent() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); + BaseUnit = ElectricCurrentUnit.Ampere; + Units = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast<ElectricCurrentUnit>().ToArray(); + Zero = new ElectricCurrent(0, BaseUnit); + Info = new QuantityInfo<ElectricCurrentUnit>("ElectricCurrent", + new UnitInfo<ElectricCurrentUnit>[] + { + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Ampere, "Amperes", new BaseUnits(current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Centiampere, "Centiamperes", BaseUnits.Undefined), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Kiloampere, "Kiloamperes", BaseUnits.Undefined), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Megaampere, "Megaamperes", BaseUnits.Undefined), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Microampere, "Microamperes", BaseUnits.Undefined), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Milliampere, "Milliamperes", BaseUnits.Undefined), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Nanoampere, "Nanoamperes", BaseUnits.Undefined), + new UnitInfo<ElectricCurrentUnit>(ElectricCurrentUnit.Picoampere, "Picoamperes", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricCurrent(double value, ElectricCurrentUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricCurrent" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricCurrentUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. + /// </summary> + public static ElectricCurrentUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricCurrent quantity. + /// </summary> + public static ElectricCurrentUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. + /// </summary> + public static ElectricCurrent Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricCurrent AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricCurrentUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Ampere"/> + /// </summary> + public double Amperes => As(ElectricCurrentUnit.Ampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Centiampere"/> + /// </summary> + public double Centiamperes => As(ElectricCurrentUnit.Centiampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Kiloampere"/> + /// </summary> + public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Megaampere"/> + /// </summary> + public double Megaamperes => As(ElectricCurrentUnit.Megaampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Microampere"/> + /// </summary> + public double Microamperes => As(ElectricCurrentUnit.Microampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Milliampere"/> + /// </summary> + public double Milliamperes => As(ElectricCurrentUnit.Milliampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Nanoampere"/> + /// </summary> + public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentUnit.Picoampere"/> + /// </summary> + public double Picoamperes => As(ElectricCurrentUnit.Picoampere); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricCurrentUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Centiampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Megaampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Microampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Milliampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Nanoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Picoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Ampere, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricCurrentUnit + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Centiampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Centiampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Kiloampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Kiloampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Megaampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Megaampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Microampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Microampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Milliampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Milliampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Nanoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Nanoampere)); + unitConverter.SetConversionFunction<ElectricCurrent>(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Picoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Picoampere)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Ampere, new CultureInfo("en-US"), false, true, new string[]{"A"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Centiampere, new CultureInfo("en-US"), false, true, new string[]{"cA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Kiloampere, new CultureInfo("en-US"), false, true, new string[]{"kA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Megaampere, new CultureInfo("en-US"), false, true, new string[]{"MA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Microampere, new CultureInfo("en-US"), false, true, new string[]{"µA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Milliampere, new CultureInfo("en-US"), false, true, new string[]{"mA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Nanoampere, new CultureInfo("en-US"), false, true, new string[]{"nA"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentUnit.Picoampere, new CultureInfo("en-US"), false, true, new string[]{"pA"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricCurrentUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricCurrentUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Ampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromAmperes(QuantityValue amperes) + { + double value = (double) amperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Centiampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromCentiamperes(QuantityValue centiamperes) + { + double value = (double) centiamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Kiloampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) + { + double value = (double) kiloamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Megaampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) + { + double value = (double) megaamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Microampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) + { + double value = (double) microamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Milliampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) + { + double value = (double) milliamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Nanoampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) + { + double value = (double) nanoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrent"/> from <see cref="ElectricCurrentUnit.Picoampere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) + { + double value = (double) picoamperes; + return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricCurrentUnit" /> to <see cref="ElectricCurrent" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricCurrent unit value.</returns> + public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) + { + return new ElectricCurrent((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricCurrent Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricCurrent Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricCurrent, ElectricCurrentUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricCurrent result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCurrent result) + { + return QuantityParser.Default.TryParse<ElectricCurrent, ElectricCurrentUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricCurrentUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricCurrentUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricCurrentUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricCurrentUnit)"/> + public static bool TryParseUnit(string str, out ElectricCurrentUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricCurrentUnit unit) + { + return UnitParser.Default.TryParse<ElectricCurrentUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricCurrent operator -(ElectricCurrent right) + { + return new ElectricCurrent(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCurrent"/> from adding two <see cref="ElectricCurrent"/>.</summary> + public static ElectricCurrent operator +(ElectricCurrent left, ElectricCurrent right) + { + return new ElectricCurrent(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrent"/> from subtracting two <see cref="ElectricCurrent"/>.</summary> + public static ElectricCurrent operator -(ElectricCurrent left, ElectricCurrent right) + { + return new ElectricCurrent(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrent"/> from multiplying value and <see cref="ElectricCurrent"/>.</summary> + public static ElectricCurrent operator *(double left, ElectricCurrent right) + { + return new ElectricCurrent(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCurrent"/> from multiplying value and <see cref="ElectricCurrent"/>.</summary> + public static ElectricCurrent operator *(ElectricCurrent left, double right) + { + return new ElectricCurrent(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrent"/> from dividing <see cref="ElectricCurrent"/> by value.</summary> + public static ElectricCurrent operator /(ElectricCurrent left, double right) + { + return new ElectricCurrent(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricCurrent"/> by <see cref="ElectricCurrent"/>.</summary> + public static double operator /(ElectricCurrent left, ElectricCurrent right) + { + return left.Amperes / right.Amperes; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricCurrent left, ElectricCurrent right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricCurrent left, ElectricCurrent right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricCurrent left, ElectricCurrent right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricCurrent left, ElectricCurrent right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricCurrent"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrent, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricCurrent left, ElectricCurrent right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricCurrent"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrent, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricCurrent left, ElectricCurrent right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCurrent"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrent, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricCurrent otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCurrent"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrent, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricCurrent other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricCurrent"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricCurrent otherQuantity)) throw new ArgumentException("Expected type ElectricCurrent.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricCurrent"/> with another <see cref="ElectricCurrent"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricCurrent other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricCurrent within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricCurrent.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricCurrentUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricCurrentUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricCurrent with the specified unit.</returns> + public ElectricCurrent ToUnit(ElectricCurrentUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricCurrent"/> to another <see cref="ElectricCurrent"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricCurrent with the specified unit.</returns> + public ElectricCurrent ToUnit(ElectricCurrentUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricCurrent), Unit, typeof(ElectricCurrent), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricCurrent)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricCurrent"/> to another <see cref="ElectricCurrent"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricCurrent"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricCurrentUnit unit, [NotNullWhen(true)] out ElectricCurrent? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricCurrent? convertedOrNull = (Unit, unit) switch + { + // ElectricCurrentUnit -> BaseUnit + (ElectricCurrentUnit.Centiampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-2d, ElectricCurrentUnit.Ampere), + (ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e3d, ElectricCurrentUnit.Ampere), + (ElectricCurrentUnit.Megaampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e6d, ElectricCurrentUnit.Ampere), + (ElectricCurrentUnit.Microampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-6d, ElectricCurrentUnit.Ampere), + (ElectricCurrentUnit.Milliampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-3d, ElectricCurrentUnit.Ampere), + (ElectricCurrentUnit.Nanoampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-9d, ElectricCurrentUnit.Ampere), + (ElectricCurrentUnit.Picoampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-12d, ElectricCurrentUnit.Ampere), + + // BaseUnit -> ElectricCurrentUnit + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Centiampere) => new ElectricCurrent((_value) / 1e-2d, ElectricCurrentUnit.Centiampere), + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Kiloampere) => new ElectricCurrent((_value) / 1e3d, ElectricCurrentUnit.Kiloampere), + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Megaampere) => new ElectricCurrent((_value) / 1e6d, ElectricCurrentUnit.Megaampere), + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Microampere) => new ElectricCurrent((_value) / 1e-6d, ElectricCurrentUnit.Microampere), + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Milliampere) => new ElectricCurrent((_value) / 1e-3d, ElectricCurrentUnit.Milliampere), + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Nanoampere) => new ElectricCurrent((_value) / 1e-9d, ElectricCurrentUnit.Nanoampere), + (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Picoampere) => new ElectricCurrent((_value) / 1e-12d, ElectricCurrentUnit.Picoampere), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricCurrentUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricCurrentUnit> IQuantity<ElectricCurrentUnit>.ToUnit(ElectricCurrentUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricCurrentUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricCurrent)) + return this; + else if (conversionType == typeof(ElectricCurrentUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricCurrent.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricCurrent.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrentUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrentUnit.g.cs new file mode 100644 index 0000000000..8ddd75ca00 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrent/ElectricCurrentUnit.g.cs @@ -0,0 +1,39 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricCurrentUnit + { + Ampere = 1, + Centiampere = 2, + Kiloampere = 3, + Megaampere = 4, + Microampere = 5, + Milliampere = 6, + Nanoampere = 7, + Picoampere = 8, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensity.csproj b/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensity.csproj new file mode 100644 index 0000000000..4fd089bb2f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricCurrentDensity</Title> + <Description>Adds ElectricCurrentDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electriccurrentdensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8beda85e-3d20-5926-c060-f92913f1192e}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricCurrentDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensity.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensity.g.cs new file mode 100644 index 0000000000..98db89cb78 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensity.g.cs @@ -0,0 +1,883 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In electromagnetism, current density is the electric current per unit area of cross section. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Current_density + /// </remarks> + [DataContract] + public readonly partial struct ElectricCurrentDensity : IArithmeticQuantity<ElectricCurrentDensity, ElectricCurrentDensityUnit, double>, IEquatable<ElectricCurrentDensity>, IComparable, IComparable<ElectricCurrentDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricCurrentDensityUnit? _unit; + + static ElectricCurrentDensity() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); + BaseUnit = ElectricCurrentDensityUnit.AmperePerSquareMeter; + Units = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast<ElectricCurrentDensityUnit>().ToArray(); + Zero = new ElectricCurrentDensity(0, BaseUnit); + Info = new QuantityInfo<ElectricCurrentDensityUnit>("ElectricCurrentDensity", + new UnitInfo<ElectricCurrentDensityUnit>[] + { + new UnitInfo<ElectricCurrentDensityUnit>(ElectricCurrentDensityUnit.AmperePerSquareFoot, "AmperesPerSquareFoot", new BaseUnits(length: LengthUnit.Foot, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricCurrentDensityUnit>(ElectricCurrentDensityUnit.AmperePerSquareInch, "AmperesPerSquareInch", new BaseUnits(length: LengthUnit.Inch, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricCurrentDensityUnit>(ElectricCurrentDensityUnit.AmperePerSquareMeter, "AmperesPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricCurrentDensity(double value, ElectricCurrentDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricCurrentDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricCurrentDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. + /// </summary> + public static ElectricCurrentDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricCurrentDensity quantity. + /// </summary> + public static ElectricCurrentDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. + /// </summary> + public static ElectricCurrentDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricCurrentDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricCurrentDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentDensityUnit.AmperePerSquareFoot"/> + /// </summary> + public double AmperesPerSquareFoot => As(ElectricCurrentDensityUnit.AmperePerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentDensityUnit.AmperePerSquareInch"/> + /// </summary> + public double AmperesPerSquareInch => As(ElectricCurrentDensityUnit.AmperePerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentDensityUnit.AmperePerSquareMeter"/> + /// </summary> + public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricCurrentDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricCurrentDensity>(ElectricCurrentDensityUnit.AmperePerSquareFoot, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareMeter)); + unitConverter.SetConversionFunction<ElectricCurrentDensity>(ElectricCurrentDensityUnit.AmperePerSquareInch, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricCurrentDensity>(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricCurrentDensityUnit + unitConverter.SetConversionFunction<ElectricCurrentDensity>(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareFoot, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareFoot)); + unitConverter.SetConversionFunction<ElectricCurrentDensity>(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareInch, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareInch)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentDensityUnit.AmperePerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"A/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentDensityUnit.AmperePerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"A/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentDensityUnit.AmperePerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"A/m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricCurrentDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricCurrentDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricCurrentDensity"/> from <see cref="ElectricCurrentDensityUnit.AmperePerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentDensity FromAmperesPerSquareFoot(QuantityValue amperespersquarefoot) + { + double value = (double) amperespersquarefoot; + return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrentDensity"/> from <see cref="ElectricCurrentDensityUnit.AmperePerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentDensity FromAmperesPerSquareInch(QuantityValue amperespersquareinch) + { + double value = (double) amperespersquareinch; + return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareInch); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrentDensity"/> from <see cref="ElectricCurrentDensityUnit.AmperePerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) + { + double value = (double) amperespersquaremeter; + return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricCurrentDensityUnit" /> to <see cref="ElectricCurrentDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricCurrentDensity unit value.</returns> + public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) + { + return new ElectricCurrentDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricCurrentDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricCurrentDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricCurrentDensity, ElectricCurrentDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricCurrentDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCurrentDensity result) + { + return QuantityParser.Default.TryParse<ElectricCurrentDensity, ElectricCurrentDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricCurrentDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricCurrentDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricCurrentDensityUnit)"/> + public static bool TryParseUnit(string str, out ElectricCurrentDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricCurrentDensityUnit unit) + { + return UnitParser.Default.TryParse<ElectricCurrentDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricCurrentDensity operator -(ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentDensity"/> from adding two <see cref="ElectricCurrentDensity"/>.</summary> + public static ElectricCurrentDensity operator +(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentDensity"/> from subtracting two <see cref="ElectricCurrentDensity"/>.</summary> + public static ElectricCurrentDensity operator -(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentDensity"/> from multiplying value and <see cref="ElectricCurrentDensity"/>.</summary> + public static ElectricCurrentDensity operator *(double left, ElectricCurrentDensity right) + { + return new ElectricCurrentDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentDensity"/> from multiplying value and <see cref="ElectricCurrentDensity"/>.</summary> + public static ElectricCurrentDensity operator *(ElectricCurrentDensity left, double right) + { + return new ElectricCurrentDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentDensity"/> from dividing <see cref="ElectricCurrentDensity"/> by value.</summary> + public static ElectricCurrentDensity operator /(ElectricCurrentDensity left, double right) + { + return new ElectricCurrentDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricCurrentDensity"/> by <see cref="ElectricCurrentDensity"/>.</summary> + public static double operator /(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.AmperesPerSquareMeter / right.AmperesPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricCurrentDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricCurrentDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCurrentDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricCurrentDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCurrentDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricCurrentDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricCurrentDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricCurrentDensity otherQuantity)) throw new ArgumentException("Expected type ElectricCurrentDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricCurrentDensity"/> with another <see cref="ElectricCurrentDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricCurrentDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricCurrentDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricCurrentDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricCurrentDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricCurrentDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricCurrentDensity with the specified unit.</returns> + public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricCurrentDensity"/> to another <see cref="ElectricCurrentDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricCurrentDensity with the specified unit.</returns> + public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricCurrentDensity), Unit, typeof(ElectricCurrentDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricCurrentDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricCurrentDensity"/> to another <see cref="ElectricCurrentDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricCurrentDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricCurrentDensityUnit unit, [NotNullWhen(true)] out ElectricCurrentDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricCurrentDensity? convertedOrNull = (Unit, unit) switch + { + // ElectricCurrentDensityUnit -> BaseUnit + (ElectricCurrentDensityUnit.AmperePerSquareFoot, ElectricCurrentDensityUnit.AmperePerSquareMeter) => new ElectricCurrentDensity(_value * 1.0763910416709722e1, ElectricCurrentDensityUnit.AmperePerSquareMeter), + (ElectricCurrentDensityUnit.AmperePerSquareInch, ElectricCurrentDensityUnit.AmperePerSquareMeter) => new ElectricCurrentDensity(_value * 1.5500031000062000e3, ElectricCurrentDensityUnit.AmperePerSquareMeter), + + // BaseUnit -> ElectricCurrentDensityUnit + (ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareFoot) => new ElectricCurrentDensity(_value / 1.0763910416709722e1, ElectricCurrentDensityUnit.AmperePerSquareFoot), + (ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareInch) => new ElectricCurrentDensity(_value / 1.5500031000062000e3, ElectricCurrentDensityUnit.AmperePerSquareInch), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricCurrentDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricCurrentDensityUnit> IQuantity<ElectricCurrentDensityUnit>.ToUnit(ElectricCurrentDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricCurrentDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricCurrentDensity)) + return this; + else if (conversionType == typeof(ElectricCurrentDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricCurrentDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricCurrentDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensityUnit.g.cs new file mode 100644 index 0000000000..433e70c970 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrentDensity/ElectricCurrentDensityUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricCurrentDensityUnit + { + AmperePerSquareFoot = 1, + AmperePerSquareInch = 2, + AmperePerSquareMeter = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradient.csproj b/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradient.csproj new file mode 100644 index 0000000000..fcac0478fb --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradient.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricCurrentGradient</Title> + <Description>Adds ElectricCurrentGradient units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electriccurrentgradient unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{29df066c-c160-cd60-b10f-23a0c3bb8457}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricCurrentGradient</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradient.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradient.g.cs new file mode 100644 index 0000000000..4dc915717f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradient.g.cs @@ -0,0 +1,901 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In electromagnetism, the current gradient describes how the current changes in time. + /// </summary> + [DataContract] + public readonly partial struct ElectricCurrentGradient : IArithmeticQuantity<ElectricCurrentGradient, ElectricCurrentGradientUnit, double>, IEquatable<ElectricCurrentGradient>, IComparable, IComparable<ElectricCurrentGradient>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricCurrentGradientUnit? _unit; + + static ElectricCurrentGradient() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); + BaseUnit = ElectricCurrentGradientUnit.AmperePerSecond; + Units = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast<ElectricCurrentGradientUnit>().ToArray(); + Zero = new ElectricCurrentGradient(0, BaseUnit); + Info = new QuantityInfo<ElectricCurrentGradientUnit>("ElectricCurrentGradient", + new UnitInfo<ElectricCurrentGradientUnit>[] + { + new UnitInfo<ElectricCurrentGradientUnit>(ElectricCurrentGradientUnit.AmperePerMicrosecond, "AmperesPerMicrosecond", new BaseUnits(time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricCurrentGradientUnit>(ElectricCurrentGradientUnit.AmperePerMillisecond, "AmperesPerMillisecond", new BaseUnits(time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricCurrentGradientUnit>(ElectricCurrentGradientUnit.AmperePerNanosecond, "AmperesPerNanosecond", new BaseUnits(time: DurationUnit.Nanosecond, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricCurrentGradientUnit>(ElectricCurrentGradientUnit.AmperePerSecond, "AmperesPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricCurrentGradient(double value, ElectricCurrentGradientUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricCurrentGradient" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricCurrentGradientUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. + /// </summary> + public static ElectricCurrentGradientUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricCurrentGradient quantity. + /// </summary> + public static ElectricCurrentGradientUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. + /// </summary> + public static ElectricCurrentGradient Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricCurrentGradient AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricCurrentGradientUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentGradientUnit.AmperePerMicrosecond"/> + /// </summary> + public double AmperesPerMicrosecond => As(ElectricCurrentGradientUnit.AmperePerMicrosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentGradientUnit.AmperePerMillisecond"/> + /// </summary> + public double AmperesPerMillisecond => As(ElectricCurrentGradientUnit.AmperePerMillisecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentGradientUnit.AmperePerNanosecond"/> + /// </summary> + public double AmperesPerNanosecond => As(ElectricCurrentGradientUnit.AmperePerNanosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricCurrentGradientUnit.AmperePerSecond"/> + /// </summary> + public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricCurrentGradientUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerMicrosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerMillisecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerNanosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricCurrentGradientUnit + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMicrosecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMicrosecond)); + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMillisecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMillisecond)); + unitConverter.SetConversionFunction<ElectricCurrentGradient>(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerNanosecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerNanosecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentGradientUnit.AmperePerMicrosecond, new CultureInfo("en-US"), false, true, new string[]{"A/μs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentGradientUnit.AmperePerMillisecond, new CultureInfo("en-US"), false, true, new string[]{"A/ms"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentGradientUnit.AmperePerNanosecond, new CultureInfo("en-US"), false, true, new string[]{"A/ns"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricCurrentGradientUnit.AmperePerSecond, new CultureInfo("en-US"), false, true, new string[]{"A/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricCurrentGradientUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricCurrentGradientUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricCurrentGradient"/> from <see cref="ElectricCurrentGradientUnit.AmperePerMicrosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentGradient FromAmperesPerMicrosecond(QuantityValue amperespermicrosecond) + { + double value = (double) amperespermicrosecond; + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMicrosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrentGradient"/> from <see cref="ElectricCurrentGradientUnit.AmperePerMillisecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentGradient FromAmperesPerMillisecond(QuantityValue amperespermillisecond) + { + double value = (double) amperespermillisecond; + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMillisecond); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrentGradient"/> from <see cref="ElectricCurrentGradientUnit.AmperePerNanosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentGradient FromAmperesPerNanosecond(QuantityValue amperespernanosecond) + { + double value = (double) amperespernanosecond; + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerNanosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricCurrentGradient"/> from <see cref="ElectricCurrentGradientUnit.AmperePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) + { + double value = (double) amperespersecond; + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricCurrentGradientUnit" /> to <see cref="ElectricCurrentGradient" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricCurrentGradient unit value.</returns> + public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) + { + return new ElectricCurrentGradient((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricCurrentGradient Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricCurrentGradient Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricCurrentGradient, ElectricCurrentGradientUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricCurrentGradient result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricCurrentGradient result) + { + return QuantityParser.Default.TryParse<ElectricCurrentGradient, ElectricCurrentGradientUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricCurrentGradientUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricCurrentGradientUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricCurrentGradientUnit)"/> + public static bool TryParseUnit(string str, out ElectricCurrentGradientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricCurrentGradientUnit unit) + { + return UnitParser.Default.TryParse<ElectricCurrentGradientUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricCurrentGradient operator -(ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentGradient"/> from adding two <see cref="ElectricCurrentGradient"/>.</summary> + public static ElectricCurrentGradient operator +(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentGradient"/> from subtracting two <see cref="ElectricCurrentGradient"/>.</summary> + public static ElectricCurrentGradient operator -(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentGradient"/> from multiplying value and <see cref="ElectricCurrentGradient"/>.</summary> + public static ElectricCurrentGradient operator *(double left, ElectricCurrentGradient right) + { + return new ElectricCurrentGradient(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentGradient"/> from multiplying value and <see cref="ElectricCurrentGradient"/>.</summary> + public static ElectricCurrentGradient operator *(ElectricCurrentGradient left, double right) + { + return new ElectricCurrentGradient(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricCurrentGradient"/> from dividing <see cref="ElectricCurrentGradient"/> by value.</summary> + public static ElectricCurrentGradient operator /(ElectricCurrentGradient left, double right) + { + return new ElectricCurrentGradient(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricCurrentGradient"/> by <see cref="ElectricCurrentGradient"/>.</summary> + public static double operator /(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.AmperesPerSecond / right.AmperesPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricCurrentGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricCurrentGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCurrentGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricCurrentGradient otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricCurrentGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricCurrentGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricCurrentGradient other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricCurrentGradient"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricCurrentGradient otherQuantity)) throw new ArgumentException("Expected type ElectricCurrentGradient.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricCurrentGradient"/> with another <see cref="ElectricCurrentGradient"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricCurrentGradient other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricCurrentGradient within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricCurrentGradient.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricCurrentGradientUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricCurrentGradientUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricCurrentGradient with the specified unit.</returns> + public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricCurrentGradient"/> to another <see cref="ElectricCurrentGradient"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricCurrentGradient with the specified unit.</returns> + public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricCurrentGradient), Unit, typeof(ElectricCurrentGradient), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricCurrentGradient)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricCurrentGradient"/> to another <see cref="ElectricCurrentGradient"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricCurrentGradient"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricCurrentGradientUnit unit, [NotNullWhen(true)] out ElectricCurrentGradient? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricCurrentGradient? convertedOrNull = (Unit, unit) switch + { + // ElectricCurrentGradientUnit -> BaseUnit + (ElectricCurrentGradientUnit.AmperePerMicrosecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value * 1E6, ElectricCurrentGradientUnit.AmperePerSecond), + (ElectricCurrentGradientUnit.AmperePerMillisecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value * 1E3, ElectricCurrentGradientUnit.AmperePerSecond), + (ElectricCurrentGradientUnit.AmperePerNanosecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value * 1E9, ElectricCurrentGradientUnit.AmperePerSecond), + + // BaseUnit -> ElectricCurrentGradientUnit + (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMicrosecond) => new ElectricCurrentGradient(_value / 1E6, ElectricCurrentGradientUnit.AmperePerMicrosecond), + (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMillisecond) => new ElectricCurrentGradient(_value / 1E3, ElectricCurrentGradientUnit.AmperePerMillisecond), + (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerNanosecond) => new ElectricCurrentGradient(_value / 1E9, ElectricCurrentGradientUnit.AmperePerNanosecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricCurrentGradientUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricCurrentGradientUnit> IQuantity<ElectricCurrentGradientUnit>.ToUnit(ElectricCurrentGradientUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricCurrentGradientUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricCurrentGradient)) + return this; + else if (conversionType == typeof(ElectricCurrentGradientUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricCurrentGradient.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricCurrentGradient.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradientUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradientUnit.g.cs new file mode 100644 index 0000000000..eb247e6cfc --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricCurrentGradient/ElectricCurrentGradientUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricCurrentGradientUnit + { + AmperePerMicrosecond = 1, + AmperePerMillisecond = 2, + AmperePerNanosecond = 3, + AmperePerSecond = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricField.csproj b/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricField.csproj new file mode 100644 index 0000000000..578229f3ec --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricField.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricField</Title> + <Description>Adds ElectricField units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricfield unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{635581a6-f954-d0e4-9c68-02c1725e49d2}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricField</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricField.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricField.g.cs new file mode 100644 index 0000000000..7e4b2ff791 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricField.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// An electric field is a force field that surrounds electric charges that attracts or repels other electric charges. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Electric_field + /// </remarks> + [DataContract] + public readonly partial struct ElectricField : IArithmeticQuantity<ElectricField, ElectricFieldUnit, double>, IEquatable<ElectricField>, IComparable, IComparable<ElectricField>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricFieldUnit? _unit; + + static ElectricField() + { + BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); + BaseUnit = ElectricFieldUnit.VoltPerMeter; + Units = Enum.GetValues(typeof(ElectricFieldUnit)).Cast<ElectricFieldUnit>().ToArray(); + Zero = new ElectricField(0, BaseUnit); + Info = new QuantityInfo<ElectricFieldUnit>("ElectricField", + new UnitInfo<ElectricFieldUnit>[] + { + new UnitInfo<ElectricFieldUnit>(ElectricFieldUnit.VoltPerMeter, "VoltsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricField(double value, ElectricFieldUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricField" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricFieldUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. + /// </summary> + public static ElectricFieldUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricField quantity. + /// </summary> + public static ElectricFieldUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. + /// </summary> + public static ElectricField Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricField AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricFieldUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricFieldUnit.VoltPerMeter"/> + /// </summary> + public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricFieldUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricField>(ElectricFieldUnit.VoltPerMeter, ElectricFieldUnit.VoltPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricFieldUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricFieldUnit.VoltPerMeter, new CultureInfo("en-US"), false, true, new string[]{"V/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricFieldUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricFieldUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricField"/> from <see cref="ElectricFieldUnit.VoltPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) + { + double value = (double) voltspermeter; + return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricFieldUnit" /> to <see cref="ElectricField" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricField unit value.</returns> + public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) + { + return new ElectricField((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricField Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricField Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricField, ElectricFieldUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricField result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricField result) + { + return QuantityParser.Default.TryParse<ElectricField, ElectricFieldUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricFieldUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricFieldUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricFieldUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricFieldUnit)"/> + public static bool TryParseUnit(string str, out ElectricFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricFieldUnit unit) + { + return UnitParser.Default.TryParse<ElectricFieldUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricField operator -(ElectricField right) + { + return new ElectricField(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricField"/> from adding two <see cref="ElectricField"/>.</summary> + public static ElectricField operator +(ElectricField left, ElectricField right) + { + return new ElectricField(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricField"/> from subtracting two <see cref="ElectricField"/>.</summary> + public static ElectricField operator -(ElectricField left, ElectricField right) + { + return new ElectricField(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricField"/> from multiplying value and <see cref="ElectricField"/>.</summary> + public static ElectricField operator *(double left, ElectricField right) + { + return new ElectricField(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricField"/> from multiplying value and <see cref="ElectricField"/>.</summary> + public static ElectricField operator *(ElectricField left, double right) + { + return new ElectricField(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricField"/> from dividing <see cref="ElectricField"/> by value.</summary> + public static ElectricField operator /(ElectricField left, double right) + { + return new ElectricField(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricField"/> by <see cref="ElectricField"/>.</summary> + public static double operator /(ElectricField left, ElectricField right) + { + return left.VoltsPerMeter / right.VoltsPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricField left, ElectricField right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricField left, ElectricField right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricField left, ElectricField right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricField left, ElectricField right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricField left, ElectricField right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricField left, ElectricField right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricField otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricField other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricField"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricField otherQuantity)) throw new ArgumentException("Expected type ElectricField.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricField"/> with another <see cref="ElectricField"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricField other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricField within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricField.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricFieldUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricFieldUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricField to another ElectricField with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricField with the specified unit.</returns> + public ElectricField ToUnit(ElectricFieldUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricField"/> to another <see cref="ElectricField"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricField with the specified unit.</returns> + public ElectricField ToUnit(ElectricFieldUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricField), Unit, typeof(ElectricField), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricField)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricField"/> to another <see cref="ElectricField"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricField"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricFieldUnit unit, [NotNullWhen(true)] out ElectricField? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricField? convertedOrNull = (Unit, unit) switch + { + // ElectricFieldUnit -> BaseUnit + + // BaseUnit -> ElectricFieldUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricFieldUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricFieldUnit> IQuantity<ElectricFieldUnit>.ToUnit(ElectricFieldUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricFieldUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricField)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricField)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricField)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricField)) + return this; + else if (conversionType == typeof(ElectricFieldUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricField.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricField.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricField)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricFieldUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricFieldUnit.g.cs new file mode 100644 index 0000000000..03ac0494d0 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricField/ElectricFieldUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricFieldUnit + { + VoltPerMeter = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductance.csproj b/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductance.csproj new file mode 100644 index 0000000000..792fe898fa --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricInductance</Title> + <Description>Adds ElectricInductance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricinductance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{76bf8a97-e573-a5b5-286f-04ca7e00f8e9}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricInductance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductance.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductance.g.cs new file mode 100644 index 0000000000..b1ff32599c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductance.g.cs @@ -0,0 +1,904 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Inductance is a property of an electrical conductor which opposes a change in current. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Inductance + /// </remarks> + [DataContract] + public readonly partial struct ElectricInductance : IArithmeticQuantity<ElectricInductance, ElectricInductanceUnit, double>, IEquatable<ElectricInductance>, IComparable, IComparable<ElectricInductance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricInductanceUnit? _unit; + + static ElectricInductance() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); + BaseUnit = ElectricInductanceUnit.Henry; + Units = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast<ElectricInductanceUnit>().ToArray(); + Zero = new ElectricInductance(0, BaseUnit); + Info = new QuantityInfo<ElectricInductanceUnit>("ElectricInductance", + new UnitInfo<ElectricInductanceUnit>[] + { + new UnitInfo<ElectricInductanceUnit>(ElectricInductanceUnit.Henry, "Henries", BaseUnits.Undefined), + new UnitInfo<ElectricInductanceUnit>(ElectricInductanceUnit.Microhenry, "Microhenries", BaseUnits.Undefined), + new UnitInfo<ElectricInductanceUnit>(ElectricInductanceUnit.Millihenry, "Millihenries", BaseUnits.Undefined), + new UnitInfo<ElectricInductanceUnit>(ElectricInductanceUnit.Nanohenry, "Nanohenries", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricInductance(double value, ElectricInductanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricInductance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricInductanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. + /// </summary> + public static ElectricInductanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricInductance quantity. + /// </summary> + public static ElectricInductanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Henry. + /// </summary> + public static ElectricInductance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricInductance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricInductanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricInductanceUnit.Henry"/> + /// </summary> + public double Henries => As(ElectricInductanceUnit.Henry); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricInductanceUnit.Microhenry"/> + /// </summary> + public double Microhenries => As(ElectricInductanceUnit.Microhenry); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricInductanceUnit.Millihenry"/> + /// </summary> + public double Millihenries => As(ElectricInductanceUnit.Millihenry); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricInductanceUnit.Nanohenry"/> + /// </summary> + public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricInductanceUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Microhenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Millihenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Nanohenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Henry, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricInductanceUnit + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Microhenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Microhenry)); + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Millihenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Millihenry)); + unitConverter.SetConversionFunction<ElectricInductance>(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Nanohenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Nanohenry)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricInductanceUnit.Henry, new CultureInfo("en-US"), false, true, new string[]{"H"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricInductanceUnit.Microhenry, new CultureInfo("en-US"), false, true, new string[]{"µH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricInductanceUnit.Millihenry, new CultureInfo("en-US"), false, true, new string[]{"mH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricInductanceUnit.Nanohenry, new CultureInfo("en-US"), false, true, new string[]{"nH"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricInductanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricInductanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricInductance"/> from <see cref="ElectricInductanceUnit.Henry"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricInductance FromHenries(QuantityValue henries) + { + double value = (double) henries; + return new ElectricInductance(value, ElectricInductanceUnit.Henry); + } + + /// <summary> + /// Creates a <see cref="ElectricInductance"/> from <see cref="ElectricInductanceUnit.Microhenry"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricInductance FromMicrohenries(QuantityValue microhenries) + { + double value = (double) microhenries; + return new ElectricInductance(value, ElectricInductanceUnit.Microhenry); + } + + /// <summary> + /// Creates a <see cref="ElectricInductance"/> from <see cref="ElectricInductanceUnit.Millihenry"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricInductance FromMillihenries(QuantityValue millihenries) + { + double value = (double) millihenries; + return new ElectricInductance(value, ElectricInductanceUnit.Millihenry); + } + + /// <summary> + /// Creates a <see cref="ElectricInductance"/> from <see cref="ElectricInductanceUnit.Nanohenry"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricInductance FromNanohenries(QuantityValue nanohenries) + { + double value = (double) nanohenries; + return new ElectricInductance(value, ElectricInductanceUnit.Nanohenry); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricInductanceUnit" /> to <see cref="ElectricInductance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricInductance unit value.</returns> + public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) + { + return new ElectricInductance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricInductance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricInductance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricInductance, ElectricInductanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricInductance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricInductance result) + { + return QuantityParser.Default.TryParse<ElectricInductance, ElectricInductanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricInductanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricInductanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricInductanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricInductanceUnit)"/> + public static bool TryParseUnit(string str, out ElectricInductanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricInductanceUnit unit) + { + return UnitParser.Default.TryParse<ElectricInductanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricInductance operator -(ElectricInductance right) + { + return new ElectricInductance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricInductance"/> from adding two <see cref="ElectricInductance"/>.</summary> + public static ElectricInductance operator +(ElectricInductance left, ElectricInductance right) + { + return new ElectricInductance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricInductance"/> from subtracting two <see cref="ElectricInductance"/>.</summary> + public static ElectricInductance operator -(ElectricInductance left, ElectricInductance right) + { + return new ElectricInductance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricInductance"/> from multiplying value and <see cref="ElectricInductance"/>.</summary> + public static ElectricInductance operator *(double left, ElectricInductance right) + { + return new ElectricInductance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricInductance"/> from multiplying value and <see cref="ElectricInductance"/>.</summary> + public static ElectricInductance operator *(ElectricInductance left, double right) + { + return new ElectricInductance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricInductance"/> from dividing <see cref="ElectricInductance"/> by value.</summary> + public static ElectricInductance operator /(ElectricInductance left, double right) + { + return new ElectricInductance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricInductance"/> by <see cref="ElectricInductance"/>.</summary> + public static double operator /(ElectricInductance left, ElectricInductance right) + { + return left.Henries / right.Henries; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricInductance left, ElectricInductance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricInductance left, ElectricInductance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricInductance left, ElectricInductance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricInductance left, ElectricInductance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricInductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricInductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricInductance left, ElectricInductance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricInductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricInductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricInductance left, ElectricInductance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricInductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricInductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricInductance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricInductance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricInductance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricInductance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricInductance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricInductance otherQuantity)) throw new ArgumentException("Expected type ElectricInductance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricInductance"/> with another <see cref="ElectricInductance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricInductance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricInductance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricInductance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricInductanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricInductanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricInductance to another ElectricInductance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricInductance with the specified unit.</returns> + public ElectricInductance ToUnit(ElectricInductanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricInductance"/> to another <see cref="ElectricInductance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricInductance with the specified unit.</returns> + public ElectricInductance ToUnit(ElectricInductanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricInductance), Unit, typeof(ElectricInductance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricInductance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricInductance"/> to another <see cref="ElectricInductance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricInductance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricInductanceUnit unit, [NotNullWhen(true)] out ElectricInductance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricInductance? convertedOrNull = (Unit, unit) switch + { + // ElectricInductanceUnit -> BaseUnit + (ElectricInductanceUnit.Microhenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-6d, ElectricInductanceUnit.Henry), + (ElectricInductanceUnit.Millihenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-3d, ElectricInductanceUnit.Henry), + (ElectricInductanceUnit.Nanohenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-9d, ElectricInductanceUnit.Henry), + + // BaseUnit -> ElectricInductanceUnit + (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Microhenry) => new ElectricInductance((_value) / 1e-6d, ElectricInductanceUnit.Microhenry), + (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Millihenry) => new ElectricInductance((_value) / 1e-3d, ElectricInductanceUnit.Millihenry), + (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Nanohenry) => new ElectricInductance((_value) / 1e-9d, ElectricInductanceUnit.Nanohenry), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricInductanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricInductanceUnit> IQuantity<ElectricInductanceUnit>.ToUnit(ElectricInductanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricInductanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricInductance)) + return this; + else if (conversionType == typeof(ElectricInductanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricInductance.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricInductance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductanceUnit.g.cs new file mode 100644 index 0000000000..38e85791db --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricInductance/ElectricInductanceUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricInductanceUnit + { + Henry = 1, + Microhenry = 2, + Millihenry = 3, + Nanohenry = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotential.csproj b/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotential.csproj new file mode 100644 index 0000000000..ebdbf437a6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotential.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricPotential</Title> + <Description>Adds ElectricPotential units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricpotential unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{66c94dc2-e546-9737-a45b-4bc60fe0e536}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricPotential</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotential.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotential.g.cs new file mode 100644 index 0000000000..591b8add61 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotential.g.cs @@ -0,0 +1,927 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct ElectricPotential : IArithmeticQuantity<ElectricPotential, ElectricPotentialUnit, double>, IEquatable<ElectricPotential>, IComparable, IComparable<ElectricPotential>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricPotentialUnit? _unit; + + static ElectricPotential() + { + BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); + BaseUnit = ElectricPotentialUnit.Volt; + Units = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast<ElectricPotentialUnit>().ToArray(); + Zero = new ElectricPotential(0, BaseUnit); + Info = new QuantityInfo<ElectricPotentialUnit>("ElectricPotential", + new UnitInfo<ElectricPotentialUnit>[] + { + new UnitInfo<ElectricPotentialUnit>(ElectricPotentialUnit.Kilovolt, "Kilovolts", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialUnit>(ElectricPotentialUnit.Megavolt, "Megavolts", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialUnit>(ElectricPotentialUnit.Microvolt, "Microvolts", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialUnit>(ElectricPotentialUnit.Millivolt, "Millivolts", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialUnit>(ElectricPotentialUnit.Volt, "Volts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricPotential(double value, ElectricPotentialUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricPotential" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricPotentialUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. + /// </summary> + public static ElectricPotentialUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricPotential quantity. + /// </summary> + public static ElectricPotentialUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Volt. + /// </summary> + public static ElectricPotential Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricPotential AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricPotentialUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialUnit.Kilovolt"/> + /// </summary> + public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialUnit.Megavolt"/> + /// </summary> + public double Megavolts => As(ElectricPotentialUnit.Megavolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialUnit.Microvolt"/> + /// </summary> + public double Microvolts => As(ElectricPotentialUnit.Microvolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialUnit.Millivolt"/> + /// </summary> + public double Millivolts => As(ElectricPotentialUnit.Millivolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialUnit.Volt"/> + /// </summary> + public double Volts => As(ElectricPotentialUnit.Volt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricPotentialUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Kilovolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Megavolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Microvolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Millivolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Volt, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricPotentialUnit + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Kilovolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Kilovolt)); + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Megavolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Megavolt)); + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Microvolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Microvolt)); + unitConverter.SetConversionFunction<ElectricPotential>(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Millivolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Millivolt)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Kilovolt, new CultureInfo("en-US"), false, true, new string[]{"kV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Kilovolt, new CultureInfo("ru-RU"), false, true, new string[]{"кВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Megavolt, new CultureInfo("en-US"), false, true, new string[]{"MV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Megavolt, new CultureInfo("ru-RU"), false, true, new string[]{"МВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Microvolt, new CultureInfo("en-US"), false, true, new string[]{"µV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Microvolt, new CultureInfo("ru-RU"), false, true, new string[]{"мкВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Millivolt, new CultureInfo("en-US"), false, true, new string[]{"mV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Millivolt, new CultureInfo("ru-RU"), false, true, new string[]{"мВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Volt, new CultureInfo("en-US"), false, true, new string[]{"V"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialUnit.Volt, new CultureInfo("ru-RU"), false, true, new string[]{"В"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricPotentialUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricPotentialUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricPotential"/> from <see cref="ElectricPotentialUnit.Kilovolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotential FromKilovolts(QuantityValue kilovolts) + { + double value = (double) kilovolts; + return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); + } + + /// <summary> + /// Creates a <see cref="ElectricPotential"/> from <see cref="ElectricPotentialUnit.Megavolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotential FromMegavolts(QuantityValue megavolts) + { + double value = (double) megavolts; + return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); + } + + /// <summary> + /// Creates a <see cref="ElectricPotential"/> from <see cref="ElectricPotentialUnit.Microvolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotential FromMicrovolts(QuantityValue microvolts) + { + double value = (double) microvolts; + return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); + } + + /// <summary> + /// Creates a <see cref="ElectricPotential"/> from <see cref="ElectricPotentialUnit.Millivolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotential FromMillivolts(QuantityValue millivolts) + { + double value = (double) millivolts; + return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); + } + + /// <summary> + /// Creates a <see cref="ElectricPotential"/> from <see cref="ElectricPotentialUnit.Volt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotential FromVolts(QuantityValue volts) + { + double value = (double) volts; + return new ElectricPotential(value, ElectricPotentialUnit.Volt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricPotentialUnit" /> to <see cref="ElectricPotential" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricPotential unit value.</returns> + public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) + { + return new ElectricPotential((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricPotential Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricPotential Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricPotential, ElectricPotentialUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricPotential result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotential result) + { + return QuantityParser.Default.TryParse<ElectricPotential, ElectricPotentialUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricPotentialUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricPotentialUnit)"/> + public static bool TryParseUnit(string str, out ElectricPotentialUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialUnit unit) + { + return UnitParser.Default.TryParse<ElectricPotentialUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricPotential operator -(ElectricPotential right) + { + return new ElectricPotential(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotential"/> from adding two <see cref="ElectricPotential"/>.</summary> + public static ElectricPotential operator +(ElectricPotential left, ElectricPotential right) + { + return new ElectricPotential(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotential"/> from subtracting two <see cref="ElectricPotential"/>.</summary> + public static ElectricPotential operator -(ElectricPotential left, ElectricPotential right) + { + return new ElectricPotential(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotential"/> from multiplying value and <see cref="ElectricPotential"/>.</summary> + public static ElectricPotential operator *(double left, ElectricPotential right) + { + return new ElectricPotential(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotential"/> from multiplying value and <see cref="ElectricPotential"/>.</summary> + public static ElectricPotential operator *(ElectricPotential left, double right) + { + return new ElectricPotential(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotential"/> from dividing <see cref="ElectricPotential"/> by value.</summary> + public static ElectricPotential operator /(ElectricPotential left, double right) + { + return new ElectricPotential(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricPotential"/> by <see cref="ElectricPotential"/>.</summary> + public static double operator /(ElectricPotential left, ElectricPotential right) + { + return left.Volts / right.Volts; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricPotential left, ElectricPotential right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricPotential left, ElectricPotential right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricPotential left, ElectricPotential right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricPotential left, ElectricPotential right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricPotential"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotential, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricPotential left, ElectricPotential right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricPotential"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotential, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricPotential left, ElectricPotential right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotential"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotential, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricPotential otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotential"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotential, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricPotential other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricPotential"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricPotential otherQuantity)) throw new ArgumentException("Expected type ElectricPotential.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricPotential"/> with another <see cref="ElectricPotential"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricPotential other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricPotential within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricPotential.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricPotentialUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricPotentialUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricPotential to another ElectricPotential with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricPotential with the specified unit.</returns> + public ElectricPotential ToUnit(ElectricPotentialUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricPotential"/> to another <see cref="ElectricPotential"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricPotential with the specified unit.</returns> + public ElectricPotential ToUnit(ElectricPotentialUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricPotential), Unit, typeof(ElectricPotential), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricPotential)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricPotential"/> to another <see cref="ElectricPotential"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricPotential"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricPotentialUnit unit, [NotNullWhen(true)] out ElectricPotential? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricPotential? convertedOrNull = (Unit, unit) switch + { + // ElectricPotentialUnit -> BaseUnit + (ElectricPotentialUnit.Kilovolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e3d, ElectricPotentialUnit.Volt), + (ElectricPotentialUnit.Megavolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e6d, ElectricPotentialUnit.Volt), + (ElectricPotentialUnit.Microvolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e-6d, ElectricPotentialUnit.Volt), + (ElectricPotentialUnit.Millivolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e-3d, ElectricPotentialUnit.Volt), + + // BaseUnit -> ElectricPotentialUnit + (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Kilovolt) => new ElectricPotential((_value) / 1e3d, ElectricPotentialUnit.Kilovolt), + (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Megavolt) => new ElectricPotential((_value) / 1e6d, ElectricPotentialUnit.Megavolt), + (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Microvolt) => new ElectricPotential((_value) / 1e-6d, ElectricPotentialUnit.Microvolt), + (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Millivolt) => new ElectricPotential((_value) / 1e-3d, ElectricPotentialUnit.Millivolt), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricPotentialUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricPotentialUnit> IQuantity<ElectricPotentialUnit>.ToUnit(ElectricPotentialUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricPotentialUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricPotential)) + return this; + else if (conversionType == typeof(ElectricPotentialUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricPotential.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricPotential.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotentialUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotentialUnit.g.cs new file mode 100644 index 0000000000..187e8bb192 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotential/ElectricPotentialUnit.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricPotentialUnit + { + Kilovolt = 1, + Megavolt = 2, + Microvolt = 3, + Millivolt = 4, + Volt = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAc.csproj b/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAc.csproj new file mode 100644 index 0000000000..ea1c1a5fa6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAc.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricPotentialAc</Title> + <Description>Adds ElectricPotentialAc units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricpotentialac unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{ab1339ec-f1d8-6abf-093e-1525ee231a9d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricPotentialAc</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAc.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAc.g.cs new file mode 100644 index 0000000000..a518c46594 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAc.g.cs @@ -0,0 +1,922 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The Electric Potential of a system known to use Alternating Current. + /// </summary> + [DataContract] + public readonly partial struct ElectricPotentialAc : IArithmeticQuantity<ElectricPotentialAc, ElectricPotentialAcUnit, double>, IEquatable<ElectricPotentialAc>, IComparable, IComparable<ElectricPotentialAc>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricPotentialAcUnit? _unit; + + static ElectricPotentialAc() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = ElectricPotentialAcUnit.VoltAc; + Units = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast<ElectricPotentialAcUnit>().ToArray(); + Zero = new ElectricPotentialAc(0, BaseUnit); + Info = new QuantityInfo<ElectricPotentialAcUnit>("ElectricPotentialAc", + new UnitInfo<ElectricPotentialAcUnit>[] + { + new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.KilovoltAc, "KilovoltsAc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.MegavoltAc, "MegavoltsAc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.MicrovoltAc, "MicrovoltsAc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.MillivoltAc, "MillivoltsAc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.VoltAc, "VoltsAc", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricPotentialAc(double value, ElectricPotentialAcUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricPotentialAc" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricPotentialAcUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value. + /// </summary> + public static ElectricPotentialAcUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricPotentialAc quantity. + /// </summary> + public static ElectricPotentialAcUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltAc. + /// </summary> + public static ElectricPotentialAc Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricPotentialAc AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricPotentialAcUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialAcUnit.KilovoltAc"/> + /// </summary> + public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialAcUnit.MegavoltAc"/> + /// </summary> + public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialAcUnit.MicrovoltAc"/> + /// </summary> + public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialAcUnit.MillivoltAc"/> + /// </summary> + public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialAcUnit.VoltAc"/> + /// </summary> + public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricPotentialAcUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.KilovoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.VoltAc)); + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.MegavoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.VoltAc)); + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.MicrovoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.VoltAc)); + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.MillivoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.VoltAc)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.VoltAc, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricPotentialAcUnit + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.KilovoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.KilovoltAc)); + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MegavoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.MegavoltAc)); + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MicrovoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.MicrovoltAc)); + unitConverter.SetConversionFunction<ElectricPotentialAc>(ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MillivoltAc, quantity => quantity.ToUnit(ElectricPotentialAcUnit.MillivoltAc)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialAcUnit.KilovoltAc, new CultureInfo("en-US"), false, true, new string[]{"kVac"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialAcUnit.MegavoltAc, new CultureInfo("en-US"), false, true, new string[]{"MVac"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialAcUnit.MicrovoltAc, new CultureInfo("en-US"), false, true, new string[]{"µVac"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialAcUnit.MillivoltAc, new CultureInfo("en-US"), false, true, new string[]{"mVac"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialAcUnit.VoltAc, new CultureInfo("en-US"), false, true, new string[]{"Vac"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricPotentialAcUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricPotentialAcUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricPotentialAc"/> from <see cref="ElectricPotentialAcUnit.KilovoltAc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) + { + double value = (double) kilovoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialAc"/> from <see cref="ElectricPotentialAcUnit.MegavoltAc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) + { + double value = (double) megavoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialAc"/> from <see cref="ElectricPotentialAcUnit.MicrovoltAc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) + { + double value = (double) microvoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialAc"/> from <see cref="ElectricPotentialAcUnit.MillivoltAc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) + { + double value = (double) millivoltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialAc"/> from <see cref="ElectricPotentialAcUnit.VoltAc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) + { + double value = (double) voltsac; + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricPotentialAcUnit" /> to <see cref="ElectricPotentialAc" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricPotentialAc unit value.</returns> + public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) + { + return new ElectricPotentialAc((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricPotentialAc Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricPotentialAc Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricPotentialAc, ElectricPotentialAcUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricPotentialAc result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotentialAc result) + { + return QuantityParser.Default.TryParse<ElectricPotentialAc, ElectricPotentialAcUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialAcUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricPotentialAcUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricPotentialAcUnit)"/> + public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialAcUnit unit) + { + return UnitParser.Default.TryParse<ElectricPotentialAcUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricPotentialAc operator -(ElectricPotentialAc right) + { + return new ElectricPotentialAc(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialAc"/> from adding two <see cref="ElectricPotentialAc"/>.</summary> + public static ElectricPotentialAc operator +(ElectricPotentialAc left, ElectricPotentialAc right) + { + return new ElectricPotentialAc(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialAc"/> from subtracting two <see cref="ElectricPotentialAc"/>.</summary> + public static ElectricPotentialAc operator -(ElectricPotentialAc left, ElectricPotentialAc right) + { + return new ElectricPotentialAc(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialAc"/> from multiplying value and <see cref="ElectricPotentialAc"/>.</summary> + public static ElectricPotentialAc operator *(double left, ElectricPotentialAc right) + { + return new ElectricPotentialAc(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialAc"/> from multiplying value and <see cref="ElectricPotentialAc"/>.</summary> + public static ElectricPotentialAc operator *(ElectricPotentialAc left, double right) + { + return new ElectricPotentialAc(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialAc"/> from dividing <see cref="ElectricPotentialAc"/> by value.</summary> + public static ElectricPotentialAc operator /(ElectricPotentialAc left, double right) + { + return new ElectricPotentialAc(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricPotentialAc"/> by <see cref="ElectricPotentialAc"/>.</summary> + public static double operator /(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.VoltsAc / right.VoltsAc; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialAc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricPotentialAc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialAc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricPotentialAc otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialAc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricPotentialAc other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricPotentialAc"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricPotentialAc otherQuantity)) throw new ArgumentException("Expected type ElectricPotentialAc.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricPotentialAc"/> with another <see cref="ElectricPotentialAc"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricPotentialAc other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricPotentialAc within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricPotentialAc.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricPotentialAcUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricPotentialAcUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricPotentialAc with the specified unit.</returns> + public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricPotentialAc"/> to another <see cref="ElectricPotentialAc"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricPotentialAc with the specified unit.</returns> + public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricPotentialAc), Unit, typeof(ElectricPotentialAc), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricPotentialAc)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricPotentialAc"/> to another <see cref="ElectricPotentialAc"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricPotentialAc"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricPotentialAcUnit unit, [NotNullWhen(true)] out ElectricPotentialAc? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricPotentialAc? convertedOrNull = (Unit, unit) switch + { + // ElectricPotentialAcUnit -> BaseUnit + (ElectricPotentialAcUnit.KilovoltAc, ElectricPotentialAcUnit.VoltAc) => new ElectricPotentialAc((_value) * 1e3d, ElectricPotentialAcUnit.VoltAc), + (ElectricPotentialAcUnit.MegavoltAc, ElectricPotentialAcUnit.VoltAc) => new ElectricPotentialAc((_value) * 1e6d, ElectricPotentialAcUnit.VoltAc), + (ElectricPotentialAcUnit.MicrovoltAc, ElectricPotentialAcUnit.VoltAc) => new ElectricPotentialAc((_value) * 1e-6d, ElectricPotentialAcUnit.VoltAc), + (ElectricPotentialAcUnit.MillivoltAc, ElectricPotentialAcUnit.VoltAc) => new ElectricPotentialAc((_value) * 1e-3d, ElectricPotentialAcUnit.VoltAc), + + // BaseUnit -> ElectricPotentialAcUnit + (ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.KilovoltAc) => new ElectricPotentialAc((_value) / 1e3d, ElectricPotentialAcUnit.KilovoltAc), + (ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MegavoltAc) => new ElectricPotentialAc((_value) / 1e6d, ElectricPotentialAcUnit.MegavoltAc), + (ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MicrovoltAc) => new ElectricPotentialAc((_value) / 1e-6d, ElectricPotentialAcUnit.MicrovoltAc), + (ElectricPotentialAcUnit.VoltAc, ElectricPotentialAcUnit.MillivoltAc) => new ElectricPotentialAc((_value) / 1e-3d, ElectricPotentialAcUnit.MillivoltAc), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricPotentialAcUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricPotentialAcUnit> IQuantity<ElectricPotentialAcUnit>.ToUnit(ElectricPotentialAcUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricPotentialAcUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricPotentialAc)) + return this; + else if (conversionType == typeof(ElectricPotentialAcUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricPotentialAc.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricPotentialAc.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAcUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAcUnit.g.cs new file mode 100644 index 0000000000..ada8068172 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialAc/ElectricPotentialAcUnit.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricPotentialAcUnit + { + KilovoltAc = 1, + MegavoltAc = 2, + MicrovoltAc = 3, + MillivoltAc = 4, + VoltAc = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRate.csproj b/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRate.csproj new file mode 100644 index 0000000000..45c9bad36f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRate.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricPotentialChangeRate</Title> + <Description>Adds ElectricPotentialChangeRate units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricpotentialchangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{679517ca-9d0b-0ec2-35ae-95230281cfba}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricPotentialChangeRate</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRate.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRate.g.cs new file mode 100644 index 0000000000..87e3723a52 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRate.g.cs @@ -0,0 +1,1237 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// ElectricPotential change rate is the ratio of the electric potential change to the time during which the change occurred (value of electric potential changes per unit time). + /// </summary> + [DataContract] + public readonly partial struct ElectricPotentialChangeRate : IArithmeticQuantity<ElectricPotentialChangeRate, ElectricPotentialChangeRateUnit, double>, IEquatable<ElectricPotentialChangeRate>, IComparable, IComparable<ElectricPotentialChangeRate>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricPotentialChangeRateUnit? _unit; + + static ElectricPotentialChangeRate() + { + BaseDimensions = new BaseDimensions(2, 1, -4, -1, 0, 0, 0); + BaseUnit = ElectricPotentialChangeRateUnit.VoltPerSecond; + Units = Enum.GetValues(typeof(ElectricPotentialChangeRateUnit)).Cast<ElectricPotentialChangeRateUnit>().ToArray(); + Zero = new ElectricPotentialChangeRate(0, BaseUnit); + Info = new QuantityInfo<ElectricPotentialChangeRateUnit>("ElectricPotentialChangeRate", + new UnitInfo<ElectricPotentialChangeRateUnit>[] + { + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.KilovoltPerHour, "KilovoltsPerHours", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, "KilovoltsPerMicroseconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.KilovoltPerMinute, "KilovoltsPerMinutes", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.KilovoltPerSecond, "KilovoltsPerSeconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MegavoltPerHour, "MegavoltsPerHours", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, "MegavoltsPerMicroseconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MegavoltPerMinute, "MegavoltsPerMinutes", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MegavoltPerSecond, "MegavoltsPerSeconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MicrovoltPerHour, "MicrovoltsPerHours", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, "MicrovoltsPerMicroseconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, "MicrovoltsPerMinutes", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, "MicrovoltsPerSeconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MillivoltPerHour, "MillivoltsPerHours", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, "MillivoltsPerMicroseconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MillivoltPerMinute, "MillivoltsPerMinutes", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.MillivoltPerSecond, "MillivoltsPerSeconds", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.VoltPerHour, "VoltsPerHours", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, "VoltsPerMicroseconds", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.VoltPerMinute, "VoltsPerMinutes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricPotentialChangeRateUnit>(ElectricPotentialChangeRateUnit.VoltPerSecond, "VoltsPerSeconds", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricPotentialChangeRate(double value, ElectricPotentialChangeRateUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricPotentialChangeRate" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricPotentialChangeRateUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricPotentialChangeRate, which is VoltPerSecond. All conversions go via this value. + /// </summary> + public static ElectricPotentialChangeRateUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricPotentialChangeRate quantity. + /// </summary> + public static ElectricPotentialChangeRateUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerSecond. + /// </summary> + public static ElectricPotentialChangeRate Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricPotentialChangeRate AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricPotentialChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricPotentialChangeRateUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricPotentialChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.KilovoltPerHour"/> + /// </summary> + public double KilovoltsPerHours => As(ElectricPotentialChangeRateUnit.KilovoltPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond"/> + /// </summary> + public double KilovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.KilovoltPerMinute"/> + /// </summary> + public double KilovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.KilovoltPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.KilovoltPerSecond"/> + /// </summary> + public double KilovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.KilovoltPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MegavoltPerHour"/> + /// </summary> + public double MegavoltsPerHours => As(ElectricPotentialChangeRateUnit.MegavoltPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond"/> + /// </summary> + public double MegavoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MegavoltPerMinute"/> + /// </summary> + public double MegavoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MegavoltPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MegavoltPerSecond"/> + /// </summary> + public double MegavoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MegavoltPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerHour"/> + /// </summary> + public double MicrovoltsPerHours => As(ElectricPotentialChangeRateUnit.MicrovoltPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond"/> + /// </summary> + public double MicrovoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerMinute"/> + /// </summary> + public double MicrovoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerSecond"/> + /// </summary> + public double MicrovoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MillivoltPerHour"/> + /// </summary> + public double MillivoltsPerHours => As(ElectricPotentialChangeRateUnit.MillivoltPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond"/> + /// </summary> + public double MillivoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MillivoltPerMinute"/> + /// </summary> + public double MillivoltsPerMinutes => As(ElectricPotentialChangeRateUnit.MillivoltPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.MillivoltPerSecond"/> + /// </summary> + public double MillivoltsPerSeconds => As(ElectricPotentialChangeRateUnit.MillivoltPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.VoltPerHour"/> + /// </summary> + public double VoltsPerHours => As(ElectricPotentialChangeRateUnit.VoltPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.VoltPerMicrosecond"/> + /// </summary> + public double VoltsPerMicroseconds => As(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.VoltPerMinute"/> + /// </summary> + public double VoltsPerMinutes => As(ElectricPotentialChangeRateUnit.VoltPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialChangeRateUnit.VoltPerSecond"/> + /// </summary> + public double VoltsPerSeconds => As(ElectricPotentialChangeRateUnit.VoltPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricPotentialChangeRateUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.KilovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.KilovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.KilovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MegavoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MegavoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MegavoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MicrovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MillivoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MillivoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.MillivoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricPotentialChangeRateUnit + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerHour)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMinute)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerHour)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMinute)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerHour)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMinute)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerHour)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMinute)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerSecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerHour)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMicrosecond)); + unitConverter.SetConversionFunction<ElectricPotentialChangeRate>(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMinute)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.KilovoltPerHour, new CultureInfo("en-US"), false, true, new string[]{"kV/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, new CultureInfo("en-US"), false, true, new string[]{"kV/μs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.KilovoltPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kV/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.KilovoltPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kV/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MegavoltPerHour, new CultureInfo("en-US"), false, true, new string[]{"MV/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, new CultureInfo("en-US"), false, true, new string[]{"MV/μs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MegavoltPerMinute, new CultureInfo("en-US"), false, true, new string[]{"MV/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MegavoltPerSecond, new CultureInfo("en-US"), false, true, new string[]{"MV/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MicrovoltPerHour, new CultureInfo("en-US"), false, true, new string[]{"µV/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, new CultureInfo("en-US"), false, true, new string[]{"µV/μs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, new CultureInfo("en-US"), false, true, new string[]{"µV/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µV/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MillivoltPerHour, new CultureInfo("en-US"), false, true, new string[]{"mV/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, new CultureInfo("en-US"), false, true, new string[]{"mV/μs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MillivoltPerMinute, new CultureInfo("en-US"), false, true, new string[]{"mV/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.MillivoltPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mV/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.VoltPerHour, new CultureInfo("en-US"), false, true, new string[]{"V/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, new CultureInfo("en-US"), false, true, new string[]{"V/μs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.VoltPerMinute, new CultureInfo("en-US"), false, true, new string[]{"V/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialChangeRateUnit.VoltPerSecond, new CultureInfo("en-US"), false, true, new string[]{"V/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.KilovoltPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromKilovoltsPerHours(QuantityValue kilovoltsperhours) + { + double value = (double) kilovoltsperhours; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerHour); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromKilovoltsPerMicroseconds(QuantityValue kilovoltspermicroseconds) + { + double value = (double) kilovoltspermicroseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.KilovoltPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromKilovoltsPerMinutes(QuantityValue kilovoltsperminutes) + { + double value = (double) kilovoltsperminutes; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMinute); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.KilovoltPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromKilovoltsPerSeconds(QuantityValue kilovoltsperseconds) + { + double value = (double) kilovoltsperseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerSecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MegavoltPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMegavoltsPerHours(QuantityValue megavoltsperhours) + { + double value = (double) megavoltsperhours; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerHour); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMegavoltsPerMicroseconds(QuantityValue megavoltspermicroseconds) + { + double value = (double) megavoltspermicroseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MegavoltPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMegavoltsPerMinutes(QuantityValue megavoltsperminutes) + { + double value = (double) megavoltsperminutes; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMinute); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MegavoltPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMegavoltsPerSeconds(QuantityValue megavoltsperseconds) + { + double value = (double) megavoltsperseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerSecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMicrovoltsPerHours(QuantityValue microvoltsperhours) + { + double value = (double) microvoltsperhours; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerHour); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMicrovoltsPerMicroseconds(QuantityValue microvoltspermicroseconds) + { + double value = (double) microvoltspermicroseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMicrovoltsPerMinutes(QuantityValue microvoltsperminutes) + { + double value = (double) microvoltsperminutes; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMinute); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MicrovoltPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMicrovoltsPerSeconds(QuantityValue microvoltsperseconds) + { + double value = (double) microvoltsperseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerSecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MillivoltPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMillivoltsPerHours(QuantityValue millivoltsperhours) + { + double value = (double) millivoltsperhours; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerHour); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMillivoltsPerMicroseconds(QuantityValue millivoltspermicroseconds) + { + double value = (double) millivoltspermicroseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MillivoltPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMillivoltsPerMinutes(QuantityValue millivoltsperminutes) + { + double value = (double) millivoltsperminutes; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMinute); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.MillivoltPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromMillivoltsPerSeconds(QuantityValue millivoltsperseconds) + { + double value = (double) millivoltsperseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerSecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.VoltPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromVoltsPerHours(QuantityValue voltsperhours) + { + double value = (double) voltsperhours; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerHour); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.VoltPerMicrosecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromVoltsPerMicroseconds(QuantityValue voltspermicroseconds) + { + double value = (double) voltspermicroseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMicrosecond); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.VoltPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromVoltsPerMinutes(QuantityValue voltsperminutes) + { + double value = (double) voltsperminutes; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMinute); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialChangeRate"/> from <see cref="ElectricPotentialChangeRateUnit.VoltPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialChangeRate FromVoltsPerSeconds(QuantityValue voltsperseconds) + { + double value = (double) voltsperseconds; + return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricPotentialChangeRateUnit" /> to <see cref="ElectricPotentialChangeRate" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricPotentialChangeRate unit value.</returns> + public static ElectricPotentialChangeRate From(QuantityValue value, ElectricPotentialChangeRateUnit fromUnit) + { + return new ElectricPotentialChangeRate((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricPotentialChangeRate Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricPotentialChangeRate Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricPotentialChangeRate, ElectricPotentialChangeRateUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricPotentialChangeRate result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotentialChangeRate result) + { + return QuantityParser.Default.TryParse<ElectricPotentialChangeRate, ElectricPotentialChangeRateUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialChangeRateUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricPotentialChangeRateUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricPotentialChangeRateUnit)"/> + public static bool TryParseUnit(string str, out ElectricPotentialChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialChangeRateUnit unit) + { + return UnitParser.Default.TryParse<ElectricPotentialChangeRateUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricPotentialChangeRate operator -(ElectricPotentialChangeRate right) + { + return new ElectricPotentialChangeRate(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialChangeRate"/> from adding two <see cref="ElectricPotentialChangeRate"/>.</summary> + public static ElectricPotentialChangeRate operator +(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return new ElectricPotentialChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialChangeRate"/> from subtracting two <see cref="ElectricPotentialChangeRate"/>.</summary> + public static ElectricPotentialChangeRate operator -(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return new ElectricPotentialChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialChangeRate"/> from multiplying value and <see cref="ElectricPotentialChangeRate"/>.</summary> + public static ElectricPotentialChangeRate operator *(double left, ElectricPotentialChangeRate right) + { + return new ElectricPotentialChangeRate(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialChangeRate"/> from multiplying value and <see cref="ElectricPotentialChangeRate"/>.</summary> + public static ElectricPotentialChangeRate operator *(ElectricPotentialChangeRate left, double right) + { + return new ElectricPotentialChangeRate(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialChangeRate"/> from dividing <see cref="ElectricPotentialChangeRate"/> by value.</summary> + public static ElectricPotentialChangeRate operator /(ElectricPotentialChangeRate left, double right) + { + return new ElectricPotentialChangeRate(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricPotentialChangeRate"/> by <see cref="ElectricPotentialChangeRate"/>.</summary> + public static double operator /(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.VoltsPerSeconds / right.VoltsPerSeconds; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricPotentialChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricPotentialChangeRate otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricPotentialChangeRate other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricPotentialChangeRate"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricPotentialChangeRate otherQuantity)) throw new ArgumentException("Expected type ElectricPotentialChangeRate.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricPotentialChangeRate"/> with another <see cref="ElectricPotentialChangeRate"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricPotentialChangeRate other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricPotentialChangeRate within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(ElectricPotentialChangeRate other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricPotentialChangeRate.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricPotentialChangeRateUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricPotentialChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricPotentialChangeRate to another ElectricPotentialChangeRate with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricPotentialChangeRate with the specified unit.</returns> + public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricPotentialChangeRate"/> to another <see cref="ElectricPotentialChangeRate"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricPotentialChangeRate with the specified unit.</returns> + public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricPotentialChangeRate), Unit, typeof(ElectricPotentialChangeRate), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricPotentialChangeRate)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricPotentialChangeRate"/> to another <see cref="ElectricPotentialChangeRate"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricPotentialChangeRate"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricPotentialChangeRateUnit unit, [NotNullWhen(true)] out ElectricPotentialChangeRate? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricPotentialChangeRate? convertedOrNull = (Unit, unit) switch + { + // ElectricPotentialChangeRateUnit -> BaseUnit + (ElectricPotentialChangeRateUnit.KilovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.KilovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.KilovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MegavoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MegavoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MegavoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MicrovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MicrovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MicrovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MillivoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MillivoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.MillivoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate(_value / 3600, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate(_value * 1E6, ElectricPotentialChangeRateUnit.VoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate(_value / 60, ElectricPotentialChangeRateUnit.VoltPerSecond), + + // BaseUnit -> ElectricPotentialChangeRateUnit + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerHour), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerMinute), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerHour), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerMinute), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerHour), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerMinute), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerHour), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerMinute), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerSecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerHour) => new ElectricPotentialChangeRate(_value * 3600, ElectricPotentialChangeRateUnit.VoltPerHour), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMicrosecond) => new ElectricPotentialChangeRate(_value / 1E6, ElectricPotentialChangeRateUnit.VoltPerMicrosecond), + (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMinute) => new ElectricPotentialChangeRate(_value * 60, ElectricPotentialChangeRateUnit.VoltPerMinute), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricPotentialChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricPotentialChangeRateUnit> IQuantity<ElectricPotentialChangeRateUnit>.ToUnit(ElectricPotentialChangeRateUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricPotentialChangeRateUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricPotentialChangeRate)) + return this; + else if (conversionType == typeof(ElectricPotentialChangeRateUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricPotentialChangeRate.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricPotentialChangeRate.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRateUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRateUnit.g.cs new file mode 100644 index 0000000000..cac18f9c78 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialChangeRate/ElectricPotentialChangeRateUnit.g.cs @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricPotentialChangeRateUnit + { + KilovoltPerHour = 1, + KilovoltPerMicrosecond = 2, + KilovoltPerMinute = 3, + KilovoltPerSecond = 4, + MegavoltPerHour = 5, + MegavoltPerMicrosecond = 6, + MegavoltPerMinute = 7, + MegavoltPerSecond = 8, + MicrovoltPerHour = 9, + MicrovoltPerMicrosecond = 10, + MicrovoltPerMinute = 11, + MicrovoltPerSecond = 12, + MillivoltPerHour = 13, + MillivoltPerMicrosecond = 14, + MillivoltPerMinute = 15, + MillivoltPerSecond = 16, + VoltPerHour = 17, + VoltPerMicrosecond = 18, + VoltPerMinute = 19, + VoltPerSecond = 20, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDc.csproj b/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDc.csproj new file mode 100644 index 0000000000..ebe4c700d3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDc.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricPotentialDc</Title> + <Description>Adds ElectricPotentialDc units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricpotentialdc unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{27ebf863-3ee7-ddb0-08ab-8577438a8f1c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricPotentialDc</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDc.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDc.g.cs new file mode 100644 index 0000000000..7c65a5220d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDc.g.cs @@ -0,0 +1,922 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The Electric Potential of a system known to use Direct Current. + /// </summary> + [DataContract] + public readonly partial struct ElectricPotentialDc : IArithmeticQuantity<ElectricPotentialDc, ElectricPotentialDcUnit, double>, IEquatable<ElectricPotentialDc>, IComparable, IComparable<ElectricPotentialDc>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricPotentialDcUnit? _unit; + + static ElectricPotentialDc() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = ElectricPotentialDcUnit.VoltDc; + Units = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast<ElectricPotentialDcUnit>().ToArray(); + Zero = new ElectricPotentialDc(0, BaseUnit); + Info = new QuantityInfo<ElectricPotentialDcUnit>("ElectricPotentialDc", + new UnitInfo<ElectricPotentialDcUnit>[] + { + new UnitInfo<ElectricPotentialDcUnit>(ElectricPotentialDcUnit.KilovoltDc, "KilovoltsDc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialDcUnit>(ElectricPotentialDcUnit.MegavoltDc, "MegavoltsDc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialDcUnit>(ElectricPotentialDcUnit.MicrovoltDc, "MicrovoltsDc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialDcUnit>(ElectricPotentialDcUnit.MillivoltDc, "MillivoltsDc", BaseUnits.Undefined), + new UnitInfo<ElectricPotentialDcUnit>(ElectricPotentialDcUnit.VoltDc, "VoltsDc", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricPotentialDc(double value, ElectricPotentialDcUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricPotentialDc" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricPotentialDcUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricPotentialDc, which is VoltDc. All conversions go via this value. + /// </summary> + public static ElectricPotentialDcUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricPotentialDc quantity. + /// </summary> + public static ElectricPotentialDcUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltDc. + /// </summary> + public static ElectricPotentialDc Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricPotentialDc AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricPotentialDcUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricPotentialDc.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialDcUnit.KilovoltDc"/> + /// </summary> + public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialDcUnit.MegavoltDc"/> + /// </summary> + public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialDcUnit.MicrovoltDc"/> + /// </summary> + public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialDcUnit.MillivoltDc"/> + /// </summary> + public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricPotentialDcUnit.VoltDc"/> + /// </summary> + public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricPotentialDcUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.KilovoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.VoltDc)); + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.MegavoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.VoltDc)); + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.MicrovoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.VoltDc)); + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.MillivoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.VoltDc)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.VoltDc, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricPotentialDcUnit + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.KilovoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.KilovoltDc)); + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MegavoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.MegavoltDc)); + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MicrovoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.MicrovoltDc)); + unitConverter.SetConversionFunction<ElectricPotentialDc>(ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MillivoltDc, quantity => quantity.ToUnit(ElectricPotentialDcUnit.MillivoltDc)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialDcUnit.KilovoltDc, new CultureInfo("en-US"), false, true, new string[]{"kVdc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialDcUnit.MegavoltDc, new CultureInfo("en-US"), false, true, new string[]{"MVdc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialDcUnit.MicrovoltDc, new CultureInfo("en-US"), false, true, new string[]{"µVdc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialDcUnit.MillivoltDc, new CultureInfo("en-US"), false, true, new string[]{"mVdc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricPotentialDcUnit.VoltDc, new CultureInfo("en-US"), false, true, new string[]{"Vdc"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricPotentialDcUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricPotentialDcUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricPotentialDc"/> from <see cref="ElectricPotentialDcUnit.KilovoltDc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) + { + double value = (double) kilovoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialDc"/> from <see cref="ElectricPotentialDcUnit.MegavoltDc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) + { + double value = (double) megavoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialDc"/> from <see cref="ElectricPotentialDcUnit.MicrovoltDc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) + { + double value = (double) microvoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialDc"/> from <see cref="ElectricPotentialDcUnit.MillivoltDc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) + { + double value = (double) millivoltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); + } + + /// <summary> + /// Creates a <see cref="ElectricPotentialDc"/> from <see cref="ElectricPotentialDcUnit.VoltDc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) + { + double value = (double) voltsdc; + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricPotentialDcUnit" /> to <see cref="ElectricPotentialDc" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricPotentialDc unit value.</returns> + public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) + { + return new ElectricPotentialDc((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricPotentialDc Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricPotentialDc Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricPotentialDc, ElectricPotentialDcUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricPotentialDc result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricPotentialDc result) + { + return QuantityParser.Default.TryParse<ElectricPotentialDc, ElectricPotentialDcUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialDcUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricPotentialDcUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricPotentialDcUnit)"/> + public static bool TryParseUnit(string str, out ElectricPotentialDcUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricPotentialDcUnit unit) + { + return UnitParser.Default.TryParse<ElectricPotentialDcUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricPotentialDc operator -(ElectricPotentialDc right) + { + return new ElectricPotentialDc(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialDc"/> from adding two <see cref="ElectricPotentialDc"/>.</summary> + public static ElectricPotentialDc operator +(ElectricPotentialDc left, ElectricPotentialDc right) + { + return new ElectricPotentialDc(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialDc"/> from subtracting two <see cref="ElectricPotentialDc"/>.</summary> + public static ElectricPotentialDc operator -(ElectricPotentialDc left, ElectricPotentialDc right) + { + return new ElectricPotentialDc(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialDc"/> from multiplying value and <see cref="ElectricPotentialDc"/>.</summary> + public static ElectricPotentialDc operator *(double left, ElectricPotentialDc right) + { + return new ElectricPotentialDc(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialDc"/> from multiplying value and <see cref="ElectricPotentialDc"/>.</summary> + public static ElectricPotentialDc operator *(ElectricPotentialDc left, double right) + { + return new ElectricPotentialDc(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricPotentialDc"/> from dividing <see cref="ElectricPotentialDc"/> by value.</summary> + public static ElectricPotentialDc operator /(ElectricPotentialDc left, double right) + { + return new ElectricPotentialDc(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricPotentialDc"/> by <see cref="ElectricPotentialDc"/>.</summary> + public static double operator /(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.VoltsDc / right.VoltsDc; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialDc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialDc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricPotentialDc left, ElectricPotentialDc right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricPotentialDc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialDc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricPotentialDc left, ElectricPotentialDc right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialDc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialDc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricPotentialDc otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricPotentialDc"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricPotentialDc, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricPotentialDc other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricPotentialDc"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricPotentialDc otherQuantity)) throw new ArgumentException("Expected type ElectricPotentialDc.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricPotentialDc"/> with another <see cref="ElectricPotentialDc"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricPotentialDc other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricPotentialDc within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricPotentialDc.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricPotentialDcUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricPotentialDcUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricPotentialDc to another ElectricPotentialDc with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricPotentialDc with the specified unit.</returns> + public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricPotentialDc"/> to another <see cref="ElectricPotentialDc"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricPotentialDc with the specified unit.</returns> + public ElectricPotentialDc ToUnit(ElectricPotentialDcUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricPotentialDc), Unit, typeof(ElectricPotentialDc), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricPotentialDc)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricPotentialDc"/> to another <see cref="ElectricPotentialDc"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricPotentialDc"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricPotentialDcUnit unit, [NotNullWhen(true)] out ElectricPotentialDc? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricPotentialDc? convertedOrNull = (Unit, unit) switch + { + // ElectricPotentialDcUnit -> BaseUnit + (ElectricPotentialDcUnit.KilovoltDc, ElectricPotentialDcUnit.VoltDc) => new ElectricPotentialDc((_value) * 1e3d, ElectricPotentialDcUnit.VoltDc), + (ElectricPotentialDcUnit.MegavoltDc, ElectricPotentialDcUnit.VoltDc) => new ElectricPotentialDc((_value) * 1e6d, ElectricPotentialDcUnit.VoltDc), + (ElectricPotentialDcUnit.MicrovoltDc, ElectricPotentialDcUnit.VoltDc) => new ElectricPotentialDc((_value) * 1e-6d, ElectricPotentialDcUnit.VoltDc), + (ElectricPotentialDcUnit.MillivoltDc, ElectricPotentialDcUnit.VoltDc) => new ElectricPotentialDc((_value) * 1e-3d, ElectricPotentialDcUnit.VoltDc), + + // BaseUnit -> ElectricPotentialDcUnit + (ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.KilovoltDc) => new ElectricPotentialDc((_value) / 1e3d, ElectricPotentialDcUnit.KilovoltDc), + (ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MegavoltDc) => new ElectricPotentialDc((_value) / 1e6d, ElectricPotentialDcUnit.MegavoltDc), + (ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MicrovoltDc) => new ElectricPotentialDc((_value) / 1e-6d, ElectricPotentialDcUnit.MicrovoltDc), + (ElectricPotentialDcUnit.VoltDc, ElectricPotentialDcUnit.MillivoltDc) => new ElectricPotentialDc((_value) / 1e-3d, ElectricPotentialDcUnit.MillivoltDc), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricPotentialDcUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialDcUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricPotentialDcUnit> IQuantity<ElectricPotentialDcUnit>.ToUnit(ElectricPotentialDcUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricPotentialDcUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialDc)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialDc)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricPotentialDc)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricPotentialDc)) + return this; + else if (conversionType == typeof(ElectricPotentialDcUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricPotentialDc.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricPotentialDc.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricPotentialDc)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDcUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDcUnit.g.cs new file mode 100644 index 0000000000..224c9c4c30 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricPotentialDc/ElectricPotentialDcUnit.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricPotentialDcUnit + { + KilovoltDc = 1, + MegavoltDc = 2, + MicrovoltDc = 3, + MillivoltDc = 4, + VoltDc = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistance.csproj b/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistance.csproj new file mode 100644 index 0000000000..35547650e6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricResistance</Title> + <Description>Adds ElectricResistance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricresistance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{78d59e90-3339-54d6-3803-f68623b72eff}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricResistance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistance.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistance.g.cs new file mode 100644 index 0000000000..c7d266ffc8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistance.g.cs @@ -0,0 +1,943 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor. + /// </summary> + [DataContract] + public readonly partial struct ElectricResistance : IArithmeticQuantity<ElectricResistance, ElectricResistanceUnit, double>, IEquatable<ElectricResistance>, IComparable, IComparable<ElectricResistance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricResistanceUnit? _unit; + + static ElectricResistance() + { + BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); + BaseUnit = ElectricResistanceUnit.Ohm; + Units = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast<ElectricResistanceUnit>().ToArray(); + Zero = new ElectricResistance(0, BaseUnit); + Info = new QuantityInfo<ElectricResistanceUnit>("ElectricResistance", + new UnitInfo<ElectricResistanceUnit>[] + { + new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Gigaohm, "Gigaohms", BaseUnits.Undefined), + new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Kiloohm, "Kiloohms", BaseUnits.Undefined), + new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Megaohm, "Megaohms", BaseUnits.Undefined), + new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Microohm, "Microohms", BaseUnits.Undefined), + new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Milliohm, "Milliohms", BaseUnits.Undefined), + new UnitInfo<ElectricResistanceUnit>(ElectricResistanceUnit.Ohm, "Ohms", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricResistance(double value, ElectricResistanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricResistance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricResistanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. + /// </summary> + public static ElectricResistanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricResistance quantity. + /// </summary> + public static ElectricResistanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. + /// </summary> + public static ElectricResistance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricResistance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricResistanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistanceUnit.Gigaohm"/> + /// </summary> + public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistanceUnit.Kiloohm"/> + /// </summary> + public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistanceUnit.Megaohm"/> + /// </summary> + public double Megaohms => As(ElectricResistanceUnit.Megaohm); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistanceUnit.Microohm"/> + /// </summary> + public double Microohms => As(ElectricResistanceUnit.Microohm); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistanceUnit.Milliohm"/> + /// </summary> + public double Milliohms => As(ElectricResistanceUnit.Milliohm); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistanceUnit.Ohm"/> + /// </summary> + public double Ohms => As(ElectricResistanceUnit.Ohm); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricResistanceUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Gigaohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Kiloohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Megaohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Microohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Milliohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Ohm, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricResistanceUnit + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Gigaohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Gigaohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Kiloohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Kiloohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Megaohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Megaohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Microohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Microohm)); + unitConverter.SetConversionFunction<ElectricResistance>(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Milliohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Milliohm)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistanceUnit.Gigaohm, new CultureInfo("en-US"), false, true, new string[]{"GΩ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistanceUnit.Kiloohm, new CultureInfo("en-US"), false, true, new string[]{"kΩ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistanceUnit.Megaohm, new CultureInfo("en-US"), false, true, new string[]{"MΩ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistanceUnit.Microohm, new CultureInfo("en-US"), false, true, new string[]{"µΩ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistanceUnit.Milliohm, new CultureInfo("en-US"), false, true, new string[]{"mΩ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistanceUnit.Ohm, new CultureInfo("en-US"), false, true, new string[]{"Ω"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricResistanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricResistanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricResistance"/> from <see cref="ElectricResistanceUnit.Gigaohm"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistance FromGigaohms(QuantityValue gigaohms) + { + double value = (double) gigaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm); + } + + /// <summary> + /// Creates a <see cref="ElectricResistance"/> from <see cref="ElectricResistanceUnit.Kiloohm"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistance FromKiloohms(QuantityValue kiloohms) + { + double value = (double) kiloohms; + return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); + } + + /// <summary> + /// Creates a <see cref="ElectricResistance"/> from <see cref="ElectricResistanceUnit.Megaohm"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistance FromMegaohms(QuantityValue megaohms) + { + double value = (double) megaohms; + return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); + } + + /// <summary> + /// Creates a <see cref="ElectricResistance"/> from <see cref="ElectricResistanceUnit.Microohm"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistance FromMicroohms(QuantityValue microohms) + { + double value = (double) microohms; + return new ElectricResistance(value, ElectricResistanceUnit.Microohm); + } + + /// <summary> + /// Creates a <see cref="ElectricResistance"/> from <see cref="ElectricResistanceUnit.Milliohm"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistance FromMilliohms(QuantityValue milliohms) + { + double value = (double) milliohms; + return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); + } + + /// <summary> + /// Creates a <see cref="ElectricResistance"/> from <see cref="ElectricResistanceUnit.Ohm"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistance FromOhms(QuantityValue ohms) + { + double value = (double) ohms; + return new ElectricResistance(value, ElectricResistanceUnit.Ohm); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricResistanceUnit" /> to <see cref="ElectricResistance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricResistance unit value.</returns> + public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) + { + return new ElectricResistance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricResistance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricResistance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricResistance, ElectricResistanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricResistance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricResistance result) + { + return QuantityParser.Default.TryParse<ElectricResistance, ElectricResistanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricResistanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricResistanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricResistanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricResistanceUnit)"/> + public static bool TryParseUnit(string str, out ElectricResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricResistanceUnit unit) + { + return UnitParser.Default.TryParse<ElectricResistanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricResistance operator -(ElectricResistance right) + { + return new ElectricResistance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricResistance"/> from adding two <see cref="ElectricResistance"/>.</summary> + public static ElectricResistance operator +(ElectricResistance left, ElectricResistance right) + { + return new ElectricResistance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricResistance"/> from subtracting two <see cref="ElectricResistance"/>.</summary> + public static ElectricResistance operator -(ElectricResistance left, ElectricResistance right) + { + return new ElectricResistance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricResistance"/> from multiplying value and <see cref="ElectricResistance"/>.</summary> + public static ElectricResistance operator *(double left, ElectricResistance right) + { + return new ElectricResistance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricResistance"/> from multiplying value and <see cref="ElectricResistance"/>.</summary> + public static ElectricResistance operator *(ElectricResistance left, double right) + { + return new ElectricResistance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricResistance"/> from dividing <see cref="ElectricResistance"/> by value.</summary> + public static ElectricResistance operator /(ElectricResistance left, double right) + { + return new ElectricResistance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricResistance"/> by <see cref="ElectricResistance"/>.</summary> + public static double operator /(ElectricResistance left, ElectricResistance right) + { + return left.Ohms / right.Ohms; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricResistance left, ElectricResistance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricResistance left, ElectricResistance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricResistance left, ElectricResistance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricResistance left, ElectricResistance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricResistance left, ElectricResistance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricResistance left, ElectricResistance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricResistance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricResistance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricResistance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricResistance otherQuantity)) throw new ArgumentException("Expected type ElectricResistance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricResistance"/> with another <see cref="ElectricResistance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricResistance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricResistance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricResistance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricResistanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricResistanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricResistance to another ElectricResistance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricResistance with the specified unit.</returns> + public ElectricResistance ToUnit(ElectricResistanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricResistance"/> to another <see cref="ElectricResistance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricResistance with the specified unit.</returns> + public ElectricResistance ToUnit(ElectricResistanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricResistance), Unit, typeof(ElectricResistance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricResistance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricResistance"/> to another <see cref="ElectricResistance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricResistance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricResistanceUnit unit, [NotNullWhen(true)] out ElectricResistance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricResistance? convertedOrNull = (Unit, unit) switch + { + // ElectricResistanceUnit -> BaseUnit + (ElectricResistanceUnit.Gigaohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e9d, ElectricResistanceUnit.Ohm), + (ElectricResistanceUnit.Kiloohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e3d, ElectricResistanceUnit.Ohm), + (ElectricResistanceUnit.Megaohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e6d, ElectricResistanceUnit.Ohm), + (ElectricResistanceUnit.Microohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e-6d, ElectricResistanceUnit.Ohm), + (ElectricResistanceUnit.Milliohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e-3d, ElectricResistanceUnit.Ohm), + + // BaseUnit -> ElectricResistanceUnit + (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Gigaohm) => new ElectricResistance((_value) / 1e9d, ElectricResistanceUnit.Gigaohm), + (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Kiloohm) => new ElectricResistance((_value) / 1e3d, ElectricResistanceUnit.Kiloohm), + (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Megaohm) => new ElectricResistance((_value) / 1e6d, ElectricResistanceUnit.Megaohm), + (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Microohm) => new ElectricResistance((_value) / 1e-6d, ElectricResistanceUnit.Microohm), + (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Milliohm) => new ElectricResistance((_value) / 1e-3d, ElectricResistanceUnit.Milliohm), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricResistanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricResistanceUnit> IQuantity<ElectricResistanceUnit>.ToUnit(ElectricResistanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricResistanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricResistance)) + return this; + else if (conversionType == typeof(ElectricResistanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricResistance.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricResistance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistanceUnit.g.cs new file mode 100644 index 0000000000..3852120742 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricResistance/ElectricResistanceUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricResistanceUnit + { + Gigaohm = 1, + Kiloohm = 2, + Megaohm = 3, + Microohm = 4, + Milliohm = 5, + Ohm = 6, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivity.csproj b/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivity.csproj new file mode 100644 index 0000000000..000dfc885d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricResistivity</Title> + <Description>Adds ElectricResistivity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricresistivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{6a4a0f45-c2b4-6be4-e44a-e78d3282359f}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricResistivity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivity.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivity.g.cs new file mode 100644 index 0000000000..18cfc643e2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivity.g.cs @@ -0,0 +1,1114 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity + /// </remarks> + [DataContract] + public readonly partial struct ElectricResistivity : IArithmeticQuantity<ElectricResistivity, ElectricResistivityUnit, double>, IEquatable<ElectricResistivity>, IComparable, IComparable<ElectricResistivity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricResistivityUnit? _unit; + + static ElectricResistivity() + { + BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); + BaseUnit = ElectricResistivityUnit.OhmMeter; + Units = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast<ElectricResistivityUnit>().ToArray(); + Zero = new ElectricResistivity(0, BaseUnit); + Info = new QuantityInfo<ElectricResistivityUnit>("ElectricResistivity", + new UnitInfo<ElectricResistivityUnit>[] + { + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.KiloohmCentimeter, "KiloohmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.KiloohmMeter, "KiloohmMeters", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.MegaohmCentimeter, "MegaohmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.MegaohmMeter, "MegaohmMeters", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.MicroohmCentimeter, "MicroohmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.MicroohmMeter, "MicroohmMeters", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.MilliohmCentimeter, "MilliohmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.MilliohmMeter, "MilliohmMeters", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.NanoohmCentimeter, "NanoohmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.NanoohmMeter, "NanoohmMeters", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.OhmCentimeter, "OhmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.OhmMeter, "OhmMeters", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.PicoohmCentimeter, "PicoohmsCentimeter", BaseUnits.Undefined), + new UnitInfo<ElectricResistivityUnit>(ElectricResistivityUnit.PicoohmMeter, "PicoohmMeters", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricResistivity(double value, ElectricResistivityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricResistivity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricResistivityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. + /// </summary> + public static ElectricResistivityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricResistivity quantity. + /// </summary> + public static ElectricResistivityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. + /// </summary> + public static ElectricResistivity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricResistivity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricResistivityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.KiloohmCentimeter"/> + /// </summary> + public double KiloohmsCentimeter => As(ElectricResistivityUnit.KiloohmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.KiloohmMeter"/> + /// </summary> + public double KiloohmMeters => As(ElectricResistivityUnit.KiloohmMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.MegaohmCentimeter"/> + /// </summary> + public double MegaohmsCentimeter => As(ElectricResistivityUnit.MegaohmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.MegaohmMeter"/> + /// </summary> + public double MegaohmMeters => As(ElectricResistivityUnit.MegaohmMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.MicroohmCentimeter"/> + /// </summary> + public double MicroohmsCentimeter => As(ElectricResistivityUnit.MicroohmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.MicroohmMeter"/> + /// </summary> + public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.MilliohmCentimeter"/> + /// </summary> + public double MilliohmsCentimeter => As(ElectricResistivityUnit.MilliohmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.MilliohmMeter"/> + /// </summary> + public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.NanoohmCentimeter"/> + /// </summary> + public double NanoohmsCentimeter => As(ElectricResistivityUnit.NanoohmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.NanoohmMeter"/> + /// </summary> + public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.OhmCentimeter"/> + /// </summary> + public double OhmsCentimeter => As(ElectricResistivityUnit.OhmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.OhmMeter"/> + /// </summary> + public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.PicoohmCentimeter"/> + /// </summary> + public double PicoohmsCentimeter => As(ElectricResistivityUnit.PicoohmCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricResistivityUnit.PicoohmMeter"/> + /// </summary> + public double PicoohmMeters => As(ElectricResistivityUnit.PicoohmMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricResistivityUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.KiloohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.KiloohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.MegaohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.MegaohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.MicroohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.MicroohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.MilliohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.MilliohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.NanoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.NanoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.PicoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.PicoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricResistivityUnit + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.KiloohmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.KiloohmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MegaohmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MegaohmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MicroohmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MicroohmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MilliohmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MilliohmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.NanoohmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.NanoohmMeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.PicoohmCentimeter)); + unitConverter.SetConversionFunction<ElectricResistivity>(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.PicoohmMeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.KiloohmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kΩ·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.KiloohmMeter, new CultureInfo("en-US"), false, true, new string[]{"kΩ·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.MegaohmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"MΩ·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.MegaohmMeter, new CultureInfo("en-US"), false, true, new string[]{"MΩ·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.MicroohmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"µΩ·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.MicroohmMeter, new CultureInfo("en-US"), false, true, new string[]{"µΩ·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.MilliohmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mΩ·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.MilliohmMeter, new CultureInfo("en-US"), false, true, new string[]{"mΩ·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.NanoohmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"nΩ·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.NanoohmMeter, new CultureInfo("en-US"), false, true, new string[]{"nΩ·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.OhmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"Ω·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.OhmMeter, new CultureInfo("en-US"), false, true, new string[]{"Ω·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.PicoohmCentimeter, new CultureInfo("en-US"), false, true, new string[]{"pΩ·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricResistivityUnit.PicoohmMeter, new CultureInfo("en-US"), false, true, new string[]{"pΩ·m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricResistivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricResistivityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.KiloohmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromKiloohmsCentimeter(QuantityValue kiloohmscentimeter) + { + double value = (double) kiloohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.KiloohmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromKiloohmMeters(QuantityValue kiloohmmeters) + { + double value = (double) kiloohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmMeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.MegaohmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromMegaohmsCentimeter(QuantityValue megaohmscentimeter) + { + double value = (double) megaohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.MegaohmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromMegaohmMeters(QuantityValue megaohmmeters) + { + double value = (double) megaohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmMeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.MicroohmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromMicroohmsCentimeter(QuantityValue microohmscentimeter) + { + double value = (double) microohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.MicroohmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) + { + double value = (double) microohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.MilliohmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromMilliohmsCentimeter(QuantityValue milliohmscentimeter) + { + double value = (double) milliohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.MilliohmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) + { + double value = (double) milliohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.NanoohmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromNanoohmsCentimeter(QuantityValue nanoohmscentimeter) + { + double value = (double) nanoohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.NanoohmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) + { + double value = (double) nanoohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.OhmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromOhmsCentimeter(QuantityValue ohmscentimeter) + { + double value = (double) ohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.OhmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.OhmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) + { + double value = (double) ohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.PicoohmCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromPicoohmsCentimeter(QuantityValue picoohmscentimeter) + { + double value = (double) picoohmscentimeter; + return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricResistivity"/> from <see cref="ElectricResistivityUnit.PicoohmMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricResistivity FromPicoohmMeters(QuantityValue picoohmmeters) + { + double value = (double) picoohmmeters; + return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricResistivityUnit" /> to <see cref="ElectricResistivity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricResistivity unit value.</returns> + public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) + { + return new ElectricResistivity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricResistivity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricResistivity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricResistivity, ElectricResistivityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricResistivity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricResistivity result) + { + return QuantityParser.Default.TryParse<ElectricResistivity, ElectricResistivityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricResistivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricResistivityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricResistivityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricResistivityUnit)"/> + public static bool TryParseUnit(string str, out ElectricResistivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricResistivityUnit unit) + { + return UnitParser.Default.TryParse<ElectricResistivityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricResistivity operator -(ElectricResistivity right) + { + return new ElectricResistivity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricResistivity"/> from adding two <see cref="ElectricResistivity"/>.</summary> + public static ElectricResistivity operator +(ElectricResistivity left, ElectricResistivity right) + { + return new ElectricResistivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricResistivity"/> from subtracting two <see cref="ElectricResistivity"/>.</summary> + public static ElectricResistivity operator -(ElectricResistivity left, ElectricResistivity right) + { + return new ElectricResistivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricResistivity"/> from multiplying value and <see cref="ElectricResistivity"/>.</summary> + public static ElectricResistivity operator *(double left, ElectricResistivity right) + { + return new ElectricResistivity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricResistivity"/> from multiplying value and <see cref="ElectricResistivity"/>.</summary> + public static ElectricResistivity operator *(ElectricResistivity left, double right) + { + return new ElectricResistivity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricResistivity"/> from dividing <see cref="ElectricResistivity"/> by value.</summary> + public static ElectricResistivity operator /(ElectricResistivity left, double right) + { + return new ElectricResistivity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricResistivity"/> by <see cref="ElectricResistivity"/>.</summary> + public static double operator /(ElectricResistivity left, ElectricResistivity right) + { + return left.OhmMeters / right.OhmMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricResistivity left, ElectricResistivity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricResistivity left, ElectricResistivity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricResistivity left, ElectricResistivity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricResistivity left, ElectricResistivity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricResistivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricResistivity left, ElectricResistivity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricResistivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricResistivity left, ElectricResistivity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricResistivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricResistivity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricResistivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricResistivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricResistivity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricResistivity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricResistivity otherQuantity)) throw new ArgumentException("Expected type ElectricResistivity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricResistivity"/> with another <see cref="ElectricResistivity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricResistivity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricResistivity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricResistivity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricResistivityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricResistivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricResistivity with the specified unit.</returns> + public ElectricResistivity ToUnit(ElectricResistivityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricResistivity"/> to another <see cref="ElectricResistivity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricResistivity with the specified unit.</returns> + public ElectricResistivity ToUnit(ElectricResistivityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricResistivity), Unit, typeof(ElectricResistivity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricResistivity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricResistivity"/> to another <see cref="ElectricResistivity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricResistivity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricResistivityUnit unit, [NotNullWhen(true)] out ElectricResistivity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricResistivity? convertedOrNull = (Unit, unit) switch + { + // ElectricResistivityUnit -> BaseUnit + (ElectricResistivityUnit.KiloohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e3d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.KiloohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e3d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.MegaohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e6d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.MegaohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e6d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.MicroohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-6d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.MicroohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-6d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.MilliohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-3d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.MilliohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-3d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.NanoohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-9d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.NanoohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-9d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.OhmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity(_value / 100, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.PicoohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-12d, ElectricResistivityUnit.OhmMeter), + (ElectricResistivityUnit.PicoohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-12d, ElectricResistivityUnit.OhmMeter), + + // BaseUnit -> ElectricResistivityUnit + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmCentimeter) => new ElectricResistivity((_value * 100) / 1e3d, ElectricResistivityUnit.KiloohmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmMeter) => new ElectricResistivity((_value) / 1e3d, ElectricResistivityUnit.KiloohmMeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmCentimeter) => new ElectricResistivity((_value * 100) / 1e6d, ElectricResistivityUnit.MegaohmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmMeter) => new ElectricResistivity((_value) / 1e6d, ElectricResistivityUnit.MegaohmMeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-6d, ElectricResistivityUnit.MicroohmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmMeter) => new ElectricResistivity((_value) / 1e-6d, ElectricResistivityUnit.MicroohmMeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-3d, ElectricResistivityUnit.MilliohmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmMeter) => new ElectricResistivity((_value) / 1e-3d, ElectricResistivityUnit.MilliohmMeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-9d, ElectricResistivityUnit.NanoohmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmMeter) => new ElectricResistivity((_value) / 1e-9d, ElectricResistivityUnit.NanoohmMeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmCentimeter) => new ElectricResistivity(_value * 100, ElectricResistivityUnit.OhmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-12d, ElectricResistivityUnit.PicoohmCentimeter), + (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmMeter) => new ElectricResistivity((_value) / 1e-12d, ElectricResistivityUnit.PicoohmMeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricResistivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricResistivityUnit> IQuantity<ElectricResistivityUnit>.ToUnit(ElectricResistivityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricResistivityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricResistivity)) + return this; + else if (conversionType == typeof(ElectricResistivityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricResistivity.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricResistivity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivityUnit.g.cs new file mode 100644 index 0000000000..c7f43cfc6c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricResistivity/ElectricResistivityUnit.g.cs @@ -0,0 +1,45 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricResistivityUnit + { + KiloohmCentimeter = 1, + KiloohmMeter = 2, + MegaohmCentimeter = 3, + MegaohmMeter = 4, + MicroohmCentimeter = 5, + MicroohmMeter = 6, + MilliohmCentimeter = 7, + MilliohmMeter = 8, + NanoohmCentimeter = 9, + NanoohmMeter = 10, + OhmCentimeter = 11, + OhmMeter = 12, + PicoohmCentimeter = 13, + PicoohmMeter = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensity.csproj b/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensity.csproj new file mode 100644 index 0000000000..b5e54cd71b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ElectricSurfaceChargeDensity</Title> + <Description>Adds ElectricSurfaceChargeDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>electricsurfacechargedensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{006e161d-aae1-2dd1-5b94-ebd45d31f50a}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ElectricSurfaceChargeDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensity.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensity.g.cs new file mode 100644 index 0000000000..e9c3b39363 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensity.g.cs @@ -0,0 +1,883 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Charge_density + /// </remarks> + [DataContract] + public readonly partial struct ElectricSurfaceChargeDensity : IArithmeticQuantity<ElectricSurfaceChargeDensity, ElectricSurfaceChargeDensityUnit, double>, IEquatable<ElectricSurfaceChargeDensity>, IComparable, IComparable<ElectricSurfaceChargeDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ElectricSurfaceChargeDensityUnit? _unit; + + static ElectricSurfaceChargeDensity() + { + BaseDimensions = new BaseDimensions(-2, 0, 1, 1, 0, 0, 0); + BaseUnit = ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter; + Units = Enum.GetValues(typeof(ElectricSurfaceChargeDensityUnit)).Cast<ElectricSurfaceChargeDensityUnit>().ToArray(); + Zero = new ElectricSurfaceChargeDensity(0, BaseUnit); + Info = new QuantityInfo<ElectricSurfaceChargeDensityUnit>("ElectricSurfaceChargeDensity", + new UnitInfo<ElectricSurfaceChargeDensityUnit>[] + { + new UnitInfo<ElectricSurfaceChargeDensityUnit>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, "CoulombsPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricSurfaceChargeDensityUnit>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, "CoulombsPerSquareInch", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + new UnitInfo<ElectricSurfaceChargeDensityUnit>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, "CoulombsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ElectricSurfaceChargeDensity(double value, ElectricSurfaceChargeDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ElectricSurfaceChargeDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ElectricSurfaceChargeDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ElectricSurfaceChargeDensity, which is CoulombPerSquareMeter. All conversions go via this value. + /// </summary> + public static ElectricSurfaceChargeDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ElectricSurfaceChargeDensity quantity. + /// </summary> + public static ElectricSurfaceChargeDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerSquareMeter. + /// </summary> + public static ElectricSurfaceChargeDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ElectricSurfaceChargeDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ElectricSurfaceChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ElectricSurfaceChargeDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ElectricSurfaceChargeDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter"/> + /// </summary> + public double CoulombsPerSquareCentimeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch"/> + /// </summary> + public double CoulombsPerSquareInch => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter"/> + /// </summary> + public double CoulombsPerSquareMeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ElectricSurfaceChargeDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<ElectricSurfaceChargeDensity>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); + unitConverter.SetConversionFunction<ElectricSurfaceChargeDensity>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ElectricSurfaceChargeDensity>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ElectricSurfaceChargeDensityUnit + unitConverter.SetConversionFunction<ElectricSurfaceChargeDensity>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter)); + unitConverter.SetConversionFunction<ElectricSurfaceChargeDensity>(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"C/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"C/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"C/m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ElectricSurfaceChargeDensity"/> from <see cref="ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(QuantityValue coulombspersquarecentimeter) + { + double value = (double) coulombspersquarecentimeter; + return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="ElectricSurfaceChargeDensity"/> from <see cref="ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(QuantityValue coulombspersquareinch) + { + double value = (double) coulombspersquareinch; + return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); + } + + /// <summary> + /// Creates a <see cref="ElectricSurfaceChargeDensity"/> from <see cref="ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(QuantityValue coulombspersquaremeter) + { + double value = (double) coulombspersquaremeter; + return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ElectricSurfaceChargeDensityUnit" /> to <see cref="ElectricSurfaceChargeDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ElectricSurfaceChargeDensity unit value.</returns> + public static ElectricSurfaceChargeDensity From(QuantityValue value, ElectricSurfaceChargeDensityUnit fromUnit) + { + return new ElectricSurfaceChargeDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ElectricSurfaceChargeDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ElectricSurfaceChargeDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ElectricSurfaceChargeDensity, ElectricSurfaceChargeDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ElectricSurfaceChargeDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ElectricSurfaceChargeDensity result) + { + return QuantityParser.Default.TryParse<ElectricSurfaceChargeDensity, ElectricSurfaceChargeDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricSurfaceChargeDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ElectricSurfaceChargeDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ElectricSurfaceChargeDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricSurfaceChargeDensityUnit)"/> + public static bool TryParseUnit(string str, out ElectricSurfaceChargeDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ElectricSurfaceChargeDensityUnit unit) + { + return UnitParser.Default.TryParse<ElectricSurfaceChargeDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ElectricSurfaceChargeDensity operator -(ElectricSurfaceChargeDensity right) + { + return new ElectricSurfaceChargeDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricSurfaceChargeDensity"/> from adding two <see cref="ElectricSurfaceChargeDensity"/>.</summary> + public static ElectricSurfaceChargeDensity operator +(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return new ElectricSurfaceChargeDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricSurfaceChargeDensity"/> from subtracting two <see cref="ElectricSurfaceChargeDensity"/>.</summary> + public static ElectricSurfaceChargeDensity operator -(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return new ElectricSurfaceChargeDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ElectricSurfaceChargeDensity"/> from multiplying value and <see cref="ElectricSurfaceChargeDensity"/>.</summary> + public static ElectricSurfaceChargeDensity operator *(double left, ElectricSurfaceChargeDensity right) + { + return new ElectricSurfaceChargeDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ElectricSurfaceChargeDensity"/> from multiplying value and <see cref="ElectricSurfaceChargeDensity"/>.</summary> + public static ElectricSurfaceChargeDensity operator *(ElectricSurfaceChargeDensity left, double right) + { + return new ElectricSurfaceChargeDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ElectricSurfaceChargeDensity"/> from dividing <see cref="ElectricSurfaceChargeDensity"/> by value.</summary> + public static ElectricSurfaceChargeDensity operator /(ElectricSurfaceChargeDensity left, double right) + { + return new ElectricSurfaceChargeDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ElectricSurfaceChargeDensity"/> by <see cref="ElectricSurfaceChargeDensity"/>.</summary> + public static double operator /(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.CoulombsPerSquareMeter / right.CoulombsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ElectricSurfaceChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricSurfaceChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ElectricSurfaceChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricSurfaceChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricSurfaceChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricSurfaceChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ElectricSurfaceChargeDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ElectricSurfaceChargeDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ElectricSurfaceChargeDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ElectricSurfaceChargeDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ElectricSurfaceChargeDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ElectricSurfaceChargeDensity otherQuantity)) throw new ArgumentException("Expected type ElectricSurfaceChargeDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ElectricSurfaceChargeDensity"/> with another <see cref="ElectricSurfaceChargeDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ElectricSurfaceChargeDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ElectricSurfaceChargeDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(ElectricSurfaceChargeDensity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ElectricSurfaceChargeDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ElectricSurfaceChargeDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ElectricSurfaceChargeDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ElectricSurfaceChargeDensity to another ElectricSurfaceChargeDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ElectricSurfaceChargeDensity with the specified unit.</returns> + public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ElectricSurfaceChargeDensity"/> to another <see cref="ElectricSurfaceChargeDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ElectricSurfaceChargeDensity with the specified unit.</returns> + public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ElectricSurfaceChargeDensity), Unit, typeof(ElectricSurfaceChargeDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ElectricSurfaceChargeDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ElectricSurfaceChargeDensity"/> to another <see cref="ElectricSurfaceChargeDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ElectricSurfaceChargeDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ElectricSurfaceChargeDensityUnit unit, [NotNullWhen(true)] out ElectricSurfaceChargeDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ElectricSurfaceChargeDensity? convertedOrNull = (Unit, unit) switch + { + // ElectricSurfaceChargeDensityUnit -> BaseUnit + (ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter) => new ElectricSurfaceChargeDensity(_value * 1.0e4, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter), + (ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter) => new ElectricSurfaceChargeDensity(_value * 1.5500031000062000e3, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter), + + // BaseUnit -> ElectricSurfaceChargeDensityUnit + (ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter) => new ElectricSurfaceChargeDensity(_value / 1.0e4, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter), + (ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch) => new ElectricSurfaceChargeDensity(_value / 1.5500031000062000e3, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ElectricSurfaceChargeDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ElectricSurfaceChargeDensityUnit> IQuantity<ElectricSurfaceChargeDensityUnit>.ToUnit(ElectricSurfaceChargeDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ElectricSurfaceChargeDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ElectricSurfaceChargeDensity)) + return this; + else if (conversionType == typeof(ElectricSurfaceChargeDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ElectricSurfaceChargeDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return ElectricSurfaceChargeDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensityUnit.g.cs new file mode 100644 index 0000000000..30c7a098de --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ElectricSurfaceChargeDensity/ElectricSurfaceChargeDensityUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ElectricSurfaceChargeDensityUnit + { + CoulombPerSquareCentimeter = 1, + CoulombPerSquareInch = 2, + CoulombPerSquareMeter = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Energy/Energy.csproj b/UnitsNet.Modular/GeneratedCode/Energy/Energy.csproj new file mode 100644 index 0000000000..7ad3f07a66 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Energy/Energy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Energy</Title> + <Description>Adds Energy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>energy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f7d3fcf2-cadc-19dd-4c4c-5a54a5102c95}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Energy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Energy/Energy.g.cs b/UnitsNet.Modular/GeneratedCode/Energy/Energy.g.cs new file mode 100644 index 0000000000..70554dfcd9 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Energy/Energy.g.cs @@ -0,0 +1,1636 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Energy : IArithmeticQuantity<Energy, EnergyUnit, double>, IEquatable<Energy>, IComparable, IComparable<Energy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly EnergyUnit? _unit; + + static Energy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + BaseUnit = EnergyUnit.Joule; + Units = Enum.GetValues(typeof(EnergyUnit)).Cast<EnergyUnit>().ToArray(); + Zero = new Energy(0, BaseUnit); + Info = new QuantityInfo<EnergyUnit>("Energy", + new UnitInfo<EnergyUnit>[] + { + new UnitInfo<EnergyUnit>(EnergyUnit.BritishThermalUnit, "BritishThermalUnits", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Calorie, "Calories", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.DecathermEc, "DecathermsEc", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.DecathermImperial, "DecathermsImperial", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.DecathermUs, "DecathermsUs", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.ElectronVolt, "ElectronVolts", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Erg, "Ergs", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.FootPound, "FootPounds", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.GigabritishThermalUnit, "GigabritishThermalUnits", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.GigaelectronVolt, "GigaelectronVolts", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Gigajoule, "Gigajoules", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.GigawattDay, "GigawattDays", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.GigawattHour, "GigawattHours", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.HorsepowerHour, "HorsepowerHours", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Joule, "Joules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), + new UnitInfo<EnergyUnit>(EnergyUnit.KilobritishThermalUnit, "KilobritishThermalUnits", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Kilocalorie, "Kilocalories", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.KiloelectronVolt, "KiloelectronVolts", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Kilojoule, "Kilojoules", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.KilowattDay, "KilowattDays", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.KilowattHour, "KilowattHours", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.MegabritishThermalUnit, "MegabritishThermalUnits", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Megacalorie, "Megacalories", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.MegaelectronVolt, "MegaelectronVolts", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Megajoule, "Megajoules", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.MegawattDay, "MegawattDays", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.MegawattHour, "MegawattHours", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Millijoule, "Millijoules", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Petajoule, "Petajoules", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.TeraelectronVolt, "TeraelectronVolts", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.Terajoule, "Terajoules", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.TerawattDay, "TerawattDays", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.TerawattHour, "TerawattHours", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.ThermEc, "ThermsEc", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.ThermImperial, "ThermsImperial", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.ThermUs, "ThermsUs", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.WattDay, "WattDays", BaseUnits.Undefined), + new UnitInfo<EnergyUnit>(EnergyUnit.WattHour, "WattHours", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Energy(double value, EnergyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Energy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<EnergyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Energy, which is Joule. All conversions go via this value. + /// </summary> + public static EnergyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Energy quantity. + /// </summary> + public static EnergyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Joule. + /// </summary> + public static Energy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Energy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<EnergyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Energy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.BritishThermalUnit"/> + /// </summary> + public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Calorie"/> + /// </summary> + public double Calories => As(EnergyUnit.Calorie); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.DecathermEc"/> + /// </summary> + public double DecathermsEc => As(EnergyUnit.DecathermEc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.DecathermImperial"/> + /// </summary> + public double DecathermsImperial => As(EnergyUnit.DecathermImperial); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.DecathermUs"/> + /// </summary> + public double DecathermsUs => As(EnergyUnit.DecathermUs); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.ElectronVolt"/> + /// </summary> + public double ElectronVolts => As(EnergyUnit.ElectronVolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Erg"/> + /// </summary> + public double Ergs => As(EnergyUnit.Erg); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.FootPound"/> + /// </summary> + public double FootPounds => As(EnergyUnit.FootPound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.GigabritishThermalUnit"/> + /// </summary> + public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.GigaelectronVolt"/> + /// </summary> + public double GigaelectronVolts => As(EnergyUnit.GigaelectronVolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Gigajoule"/> + /// </summary> + public double Gigajoules => As(EnergyUnit.Gigajoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.GigawattDay"/> + /// </summary> + public double GigawattDays => As(EnergyUnit.GigawattDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.GigawattHour"/> + /// </summary> + public double GigawattHours => As(EnergyUnit.GigawattHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.HorsepowerHour"/> + /// </summary> + public double HorsepowerHours => As(EnergyUnit.HorsepowerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Joule"/> + /// </summary> + public double Joules => As(EnergyUnit.Joule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.KilobritishThermalUnit"/> + /// </summary> + public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Kilocalorie"/> + /// </summary> + public double Kilocalories => As(EnergyUnit.Kilocalorie); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.KiloelectronVolt"/> + /// </summary> + public double KiloelectronVolts => As(EnergyUnit.KiloelectronVolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Kilojoule"/> + /// </summary> + public double Kilojoules => As(EnergyUnit.Kilojoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.KilowattDay"/> + /// </summary> + public double KilowattDays => As(EnergyUnit.KilowattDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.KilowattHour"/> + /// </summary> + public double KilowattHours => As(EnergyUnit.KilowattHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.MegabritishThermalUnit"/> + /// </summary> + public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Megacalorie"/> + /// </summary> + public double Megacalories => As(EnergyUnit.Megacalorie); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.MegaelectronVolt"/> + /// </summary> + public double MegaelectronVolts => As(EnergyUnit.MegaelectronVolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Megajoule"/> + /// </summary> + public double Megajoules => As(EnergyUnit.Megajoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.MegawattDay"/> + /// </summary> + public double MegawattDays => As(EnergyUnit.MegawattDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.MegawattHour"/> + /// </summary> + public double MegawattHours => As(EnergyUnit.MegawattHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Millijoule"/> + /// </summary> + public double Millijoules => As(EnergyUnit.Millijoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Petajoule"/> + /// </summary> + public double Petajoules => As(EnergyUnit.Petajoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.TeraelectronVolt"/> + /// </summary> + public double TeraelectronVolts => As(EnergyUnit.TeraelectronVolt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.Terajoule"/> + /// </summary> + public double Terajoules => As(EnergyUnit.Terajoule); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.TerawattDay"/> + /// </summary> + public double TerawattDays => As(EnergyUnit.TerawattDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.TerawattHour"/> + /// </summary> + public double TerawattHours => As(EnergyUnit.TerawattHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.ThermEc"/> + /// </summary> + public double ThermsEc => As(EnergyUnit.ThermEc); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.ThermImperial"/> + /// </summary> + public double ThermsImperial => As(EnergyUnit.ThermImperial); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.ThermUs"/> + /// </summary> + public double ThermsUs => As(EnergyUnit.ThermUs); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.WattDay"/> + /// </summary> + public double WattDays => As(EnergyUnit.WattDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyUnit.WattHour"/> + /// </summary> + public double WattHours => As(EnergyUnit.WattHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: EnergyUnit -> BaseUnit + unitConverter.SetConversionFunction<Energy>(EnergyUnit.BritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Calorie, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.DecathermEc, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.DecathermImperial, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.DecathermUs, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.ElectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Erg, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.FootPound, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.GigabritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.GigaelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Gigajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.GigawattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.GigawattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.HorsepowerHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.KilobritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Kilocalorie, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.KiloelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Kilojoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.KilowattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.KilowattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.MegabritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Megacalorie, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.MegaelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Megajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.MegawattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.MegawattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Millijoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Petajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.TeraelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Terajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.TerawattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.TerawattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.ThermEc, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.ThermImperial, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.ThermUs, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.WattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.WattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Joule, quantity => quantity); + + // Register in unit converter: BaseUnit -> EnergyUnit + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.BritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.BritishThermalUnit)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Calorie, quantity => quantity.ToUnit(EnergyUnit.Calorie)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.DecathermEc, quantity => quantity.ToUnit(EnergyUnit.DecathermEc)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.DecathermImperial, quantity => quantity.ToUnit(EnergyUnit.DecathermImperial)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.DecathermUs, quantity => quantity.ToUnit(EnergyUnit.DecathermUs)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.ElectronVolt, quantity => quantity.ToUnit(EnergyUnit.ElectronVolt)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Erg, quantity => quantity.ToUnit(EnergyUnit.Erg)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.FootPound, quantity => quantity.ToUnit(EnergyUnit.FootPound)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.GigabritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.GigabritishThermalUnit)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.GigaelectronVolt, quantity => quantity.ToUnit(EnergyUnit.GigaelectronVolt)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Gigajoule, quantity => quantity.ToUnit(EnergyUnit.Gigajoule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.GigawattDay, quantity => quantity.ToUnit(EnergyUnit.GigawattDay)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.GigawattHour, quantity => quantity.ToUnit(EnergyUnit.GigawattHour)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.HorsepowerHour, quantity => quantity.ToUnit(EnergyUnit.HorsepowerHour)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.KilobritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.KilobritishThermalUnit)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Kilocalorie, quantity => quantity.ToUnit(EnergyUnit.Kilocalorie)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.KiloelectronVolt, quantity => quantity.ToUnit(EnergyUnit.KiloelectronVolt)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Kilojoule, quantity => quantity.ToUnit(EnergyUnit.Kilojoule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.KilowattDay, quantity => quantity.ToUnit(EnergyUnit.KilowattDay)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.KilowattHour, quantity => quantity.ToUnit(EnergyUnit.KilowattHour)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.MegabritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.MegabritishThermalUnit)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Megacalorie, quantity => quantity.ToUnit(EnergyUnit.Megacalorie)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.MegaelectronVolt, quantity => quantity.ToUnit(EnergyUnit.MegaelectronVolt)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Megajoule, quantity => quantity.ToUnit(EnergyUnit.Megajoule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.MegawattDay, quantity => quantity.ToUnit(EnergyUnit.MegawattDay)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.MegawattHour, quantity => quantity.ToUnit(EnergyUnit.MegawattHour)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Millijoule, quantity => quantity.ToUnit(EnergyUnit.Millijoule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Petajoule, quantity => quantity.ToUnit(EnergyUnit.Petajoule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.TeraelectronVolt, quantity => quantity.ToUnit(EnergyUnit.TeraelectronVolt)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.Terajoule, quantity => quantity.ToUnit(EnergyUnit.Terajoule)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.TerawattDay, quantity => quantity.ToUnit(EnergyUnit.TerawattDay)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.TerawattHour, quantity => quantity.ToUnit(EnergyUnit.TerawattHour)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.ThermEc, quantity => quantity.ToUnit(EnergyUnit.ThermEc)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.ThermImperial, quantity => quantity.ToUnit(EnergyUnit.ThermImperial)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.ThermUs, quantity => quantity.ToUnit(EnergyUnit.ThermUs)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.WattDay, quantity => quantity.ToUnit(EnergyUnit.WattDay)); + unitConverter.SetConversionFunction<Energy>(EnergyUnit.Joule, EnergyUnit.WattHour, quantity => quantity.ToUnit(EnergyUnit.WattHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.BritishThermalUnit, new CultureInfo("en-US"), false, true, new string[]{"BTU"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Calorie, new CultureInfo("en-US"), false, true, new string[]{"cal"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.DecathermEc, new CultureInfo("en-US"), false, true, new string[]{"Dth (E.C.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.DecathermEc, new CultureInfo("ru-RU"), false, true, new string[]{"Европейский декатерм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.DecathermImperial, new CultureInfo("en-US"), false, true, new string[]{"Dth (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.DecathermImperial, new CultureInfo("ru-RU"), false, true, new string[]{"Английский декатерм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.DecathermUs, new CultureInfo("en-US"), false, true, new string[]{"Dth (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.DecathermUs, new CultureInfo("ru-RU"), false, true, new string[]{"Американский декатерм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ElectronVolt, new CultureInfo("en-US"), false, true, new string[]{"eV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ElectronVolt, new CultureInfo("ru-RU"), false, true, new string[]{"эВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Erg, new CultureInfo("en-US"), false, true, new string[]{"erg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.FootPound, new CultureInfo("en-US"), false, true, new string[]{"ft·lb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigabritishThermalUnit, new CultureInfo("en-US"), false, true, new string[]{"GBTU"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigaelectronVolt, new CultureInfo("en-US"), false, true, new string[]{"GeV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigaelectronVolt, new CultureInfo("ru-RU"), false, true, new string[]{"ГэВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Gigajoule, new CultureInfo("en-US"), false, true, new string[]{"GJ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigawattDay, new CultureInfo("en-US"), false, true, new string[]{"GWd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigawattDay, new CultureInfo("ru-RU"), false, true, new string[]{"ГВт/д"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigawattHour, new CultureInfo("en-US"), false, true, new string[]{"GWh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.GigawattHour, new CultureInfo("ru-RU"), false, true, new string[]{"ГВт/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.HorsepowerHour, new CultureInfo("en-US"), false, true, new string[]{"hp·h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Joule, new CultureInfo("en-US"), false, true, new string[]{"J"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KilobritishThermalUnit, new CultureInfo("en-US"), false, true, new string[]{"kBTU"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Kilocalorie, new CultureInfo("en-US"), false, true, new string[]{"kcal"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KiloelectronVolt, new CultureInfo("en-US"), false, true, new string[]{"keV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KiloelectronVolt, new CultureInfo("ru-RU"), false, true, new string[]{"кэВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Kilojoule, new CultureInfo("en-US"), false, true, new string[]{"kJ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KilowattDay, new CultureInfo("en-US"), false, true, new string[]{"kWd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KilowattDay, new CultureInfo("ru-RU"), false, true, new string[]{"кВт/д"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KilowattHour, new CultureInfo("en-US"), false, true, new string[]{"kWh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.KilowattHour, new CultureInfo("ru-RU"), false, true, new string[]{"кВт/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegabritishThermalUnit, new CultureInfo("en-US"), false, true, new string[]{"MBTU"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Megacalorie, new CultureInfo("en-US"), false, true, new string[]{"Mcal"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegaelectronVolt, new CultureInfo("en-US"), false, true, new string[]{"MeV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegaelectronVolt, new CultureInfo("ru-RU"), false, true, new string[]{"МэВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Megajoule, new CultureInfo("en-US"), false, true, new string[]{"MJ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegawattDay, new CultureInfo("en-US"), false, true, new string[]{"MWd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegawattDay, new CultureInfo("ru-RU"), false, true, new string[]{"МВт/д"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegawattHour, new CultureInfo("en-US"), false, true, new string[]{"MWh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.MegawattHour, new CultureInfo("ru-RU"), false, true, new string[]{"МВт/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Millijoule, new CultureInfo("en-US"), false, true, new string[]{"mJ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Petajoule, new CultureInfo("en-US"), false, true, new string[]{"PJ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.TeraelectronVolt, new CultureInfo("en-US"), false, true, new string[]{"TeV"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.TeraelectronVolt, new CultureInfo("ru-RU"), false, true, new string[]{"ТэВ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.Terajoule, new CultureInfo("en-US"), false, true, new string[]{"TJ"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.TerawattDay, new CultureInfo("en-US"), false, true, new string[]{"TWd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.TerawattDay, new CultureInfo("ru-RU"), false, true, new string[]{"ТВт/д"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.TerawattHour, new CultureInfo("en-US"), false, true, new string[]{"TWh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.TerawattHour, new CultureInfo("ru-RU"), false, true, new string[]{"ТВт/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ThermEc, new CultureInfo("en-US"), false, true, new string[]{"th (E.C.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ThermEc, new CultureInfo("ru-RU"), false, true, new string[]{"Европейский терм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ThermImperial, new CultureInfo("en-US"), false, true, new string[]{"th (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ThermImperial, new CultureInfo("ru-RU"), false, true, new string[]{"Английский терм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ThermUs, new CultureInfo("en-US"), false, true, new string[]{"th (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.ThermUs, new CultureInfo("ru-RU"), false, true, new string[]{"Американский терм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.WattDay, new CultureInfo("en-US"), false, true, new string[]{"Wd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.WattDay, new CultureInfo("ru-RU"), false, true, new string[]{"Вт/д"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.WattHour, new CultureInfo("en-US"), false, true, new string[]{"Wh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyUnit.WattHour, new CultureInfo("ru-RU"), false, true, new string[]{"Вт/ч"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(EnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(EnergyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.BritishThermalUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) + { + double value = (double) britishthermalunits; + return new Energy(value, EnergyUnit.BritishThermalUnit); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Calorie"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromCalories(QuantityValue calories) + { + double value = (double) calories; + return new Energy(value, EnergyUnit.Calorie); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.DecathermEc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromDecathermsEc(QuantityValue decathermsec) + { + double value = (double) decathermsec; + return new Energy(value, EnergyUnit.DecathermEc); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.DecathermImperial"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) + { + double value = (double) decathermsimperial; + return new Energy(value, EnergyUnit.DecathermImperial); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.DecathermUs"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromDecathermsUs(QuantityValue decathermsus) + { + double value = (double) decathermsus; + return new Energy(value, EnergyUnit.DecathermUs); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.ElectronVolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromElectronVolts(QuantityValue electronvolts) + { + double value = (double) electronvolts; + return new Energy(value, EnergyUnit.ElectronVolt); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Erg"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromErgs(QuantityValue ergs) + { + double value = (double) ergs; + return new Energy(value, EnergyUnit.Erg); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.FootPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromFootPounds(QuantityValue footpounds) + { + double value = (double) footpounds; + return new Energy(value, EnergyUnit.FootPound); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.GigabritishThermalUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) + { + double value = (double) gigabritishthermalunits; + return new Energy(value, EnergyUnit.GigabritishThermalUnit); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.GigaelectronVolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromGigaelectronVolts(QuantityValue gigaelectronvolts) + { + double value = (double) gigaelectronvolts; + return new Energy(value, EnergyUnit.GigaelectronVolt); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Gigajoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromGigajoules(QuantityValue gigajoules) + { + double value = (double) gigajoules; + return new Energy(value, EnergyUnit.Gigajoule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.GigawattDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromGigawattDays(QuantityValue gigawattdays) + { + double value = (double) gigawattdays; + return new Energy(value, EnergyUnit.GigawattDay); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.GigawattHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromGigawattHours(QuantityValue gigawatthours) + { + double value = (double) gigawatthours; + return new Energy(value, EnergyUnit.GigawattHour); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.HorsepowerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromHorsepowerHours(QuantityValue horsepowerhours) + { + double value = (double) horsepowerhours; + return new Energy(value, EnergyUnit.HorsepowerHour); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Joule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromJoules(QuantityValue joules) + { + double value = (double) joules; + return new Energy(value, EnergyUnit.Joule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.KilobritishThermalUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) + { + double value = (double) kilobritishthermalunits; + return new Energy(value, EnergyUnit.KilobritishThermalUnit); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Kilocalorie"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromKilocalories(QuantityValue kilocalories) + { + double value = (double) kilocalories; + return new Energy(value, EnergyUnit.Kilocalorie); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.KiloelectronVolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromKiloelectronVolts(QuantityValue kiloelectronvolts) + { + double value = (double) kiloelectronvolts; + return new Energy(value, EnergyUnit.KiloelectronVolt); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Kilojoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromKilojoules(QuantityValue kilojoules) + { + double value = (double) kilojoules; + return new Energy(value, EnergyUnit.Kilojoule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.KilowattDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromKilowattDays(QuantityValue kilowattdays) + { + double value = (double) kilowattdays; + return new Energy(value, EnergyUnit.KilowattDay); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.KilowattHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromKilowattHours(QuantityValue kilowatthours) + { + double value = (double) kilowatthours; + return new Energy(value, EnergyUnit.KilowattHour); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.MegabritishThermalUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) + { + double value = (double) megabritishthermalunits; + return new Energy(value, EnergyUnit.MegabritishThermalUnit); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Megacalorie"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMegacalories(QuantityValue megacalories) + { + double value = (double) megacalories; + return new Energy(value, EnergyUnit.Megacalorie); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.MegaelectronVolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMegaelectronVolts(QuantityValue megaelectronvolts) + { + double value = (double) megaelectronvolts; + return new Energy(value, EnergyUnit.MegaelectronVolt); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Megajoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMegajoules(QuantityValue megajoules) + { + double value = (double) megajoules; + return new Energy(value, EnergyUnit.Megajoule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.MegawattDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMegawattDays(QuantityValue megawattdays) + { + double value = (double) megawattdays; + return new Energy(value, EnergyUnit.MegawattDay); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.MegawattHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMegawattHours(QuantityValue megawatthours) + { + double value = (double) megawatthours; + return new Energy(value, EnergyUnit.MegawattHour); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Millijoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromMillijoules(QuantityValue millijoules) + { + double value = (double) millijoules; + return new Energy(value, EnergyUnit.Millijoule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Petajoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromPetajoules(QuantityValue petajoules) + { + double value = (double) petajoules; + return new Energy(value, EnergyUnit.Petajoule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.TeraelectronVolt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromTeraelectronVolts(QuantityValue teraelectronvolts) + { + double value = (double) teraelectronvolts; + return new Energy(value, EnergyUnit.TeraelectronVolt); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.Terajoule"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromTerajoules(QuantityValue terajoules) + { + double value = (double) terajoules; + return new Energy(value, EnergyUnit.Terajoule); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.TerawattDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromTerawattDays(QuantityValue terawattdays) + { + double value = (double) terawattdays; + return new Energy(value, EnergyUnit.TerawattDay); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.TerawattHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromTerawattHours(QuantityValue terawatthours) + { + double value = (double) terawatthours; + return new Energy(value, EnergyUnit.TerawattHour); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.ThermEc"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromThermsEc(QuantityValue thermsec) + { + double value = (double) thermsec; + return new Energy(value, EnergyUnit.ThermEc); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.ThermImperial"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromThermsImperial(QuantityValue thermsimperial) + { + double value = (double) thermsimperial; + return new Energy(value, EnergyUnit.ThermImperial); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.ThermUs"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromThermsUs(QuantityValue thermsus) + { + double value = (double) thermsus; + return new Energy(value, EnergyUnit.ThermUs); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.WattDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromWattDays(QuantityValue wattdays) + { + double value = (double) wattdays; + return new Energy(value, EnergyUnit.WattDay); + } + + /// <summary> + /// Creates a <see cref="Energy"/> from <see cref="EnergyUnit.WattHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Energy FromWattHours(QuantityValue watthours) + { + double value = (double) watthours; + return new Energy(value, EnergyUnit.WattHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="EnergyUnit" /> to <see cref="Energy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Energy unit value.</returns> + public static Energy From(QuantityValue value, EnergyUnit fromUnit) + { + return new Energy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Energy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Energy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Energy, EnergyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Energy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Energy result) + { + return QuantityParser.Default.TryParse<Energy, EnergyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static EnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static EnergyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<EnergyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.EnergyUnit)"/> + public static bool TryParseUnit(string str, out EnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out EnergyUnit unit) + { + return UnitParser.Default.TryParse<EnergyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Energy operator -(Energy right) + { + return new Energy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Energy"/> from adding two <see cref="Energy"/>.</summary> + public static Energy operator +(Energy left, Energy right) + { + return new Energy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Energy"/> from subtracting two <see cref="Energy"/>.</summary> + public static Energy operator -(Energy left, Energy right) + { + return new Energy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Energy"/> from multiplying value and <see cref="Energy"/>.</summary> + public static Energy operator *(double left, Energy right) + { + return new Energy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Energy"/> from multiplying value and <see cref="Energy"/>.</summary> + public static Energy operator *(Energy left, double right) + { + return new Energy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Energy"/> from dividing <see cref="Energy"/> by value.</summary> + public static Energy operator /(Energy left, double right) + { + return new Energy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Energy"/> by <see cref="Energy"/>.</summary> + public static double operator /(Energy left, Energy right) + { + return left.Joules / right.Joules; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Energy left, Energy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Energy left, Energy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Energy left, Energy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Energy left, Energy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Energy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Energy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Energy left, Energy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Energy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Energy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Energy left, Energy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Energy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Energy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Energy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Energy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Energy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Energy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Energy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Energy otherQuantity)) throw new ArgumentException("Expected type Energy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Energy"/> with another <see cref="Energy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Energy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Energy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Energy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(EnergyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is EnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Energy to another Energy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Energy with the specified unit.</returns> + public Energy ToUnit(EnergyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Energy"/> to another <see cref="Energy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Energy with the specified unit.</returns> + public Energy ToUnit(EnergyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Energy), Unit, typeof(Energy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Energy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Energy"/> to another <see cref="Energy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Energy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(EnergyUnit unit, [NotNullWhen(true)] out Energy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Energy? convertedOrNull = (Unit, unit) switch + { + // EnergyUnit -> BaseUnit + (EnergyUnit.BritishThermalUnit, EnergyUnit.Joule) => new Energy(_value * 1055.05585262, EnergyUnit.Joule), + (EnergyUnit.Calorie, EnergyUnit.Joule) => new Energy(_value * 4.184, EnergyUnit.Joule), + (EnergyUnit.DecathermEc, EnergyUnit.Joule) => new Energy((_value * 1.05505585262e8) * 1e1d, EnergyUnit.Joule), + (EnergyUnit.DecathermImperial, EnergyUnit.Joule) => new Energy((_value * 1.05505585257348e8) * 1e1d, EnergyUnit.Joule), + (EnergyUnit.DecathermUs, EnergyUnit.Joule) => new Energy((_value * 1.054804e8) * 1e1d, EnergyUnit.Joule), + (EnergyUnit.ElectronVolt, EnergyUnit.Joule) => new Energy(_value * 1.602176565e-19, EnergyUnit.Joule), + (EnergyUnit.Erg, EnergyUnit.Joule) => new Energy(_value * 1e-7, EnergyUnit.Joule), + (EnergyUnit.FootPound, EnergyUnit.Joule) => new Energy(_value * 1.355817948, EnergyUnit.Joule), + (EnergyUnit.GigabritishThermalUnit, EnergyUnit.Joule) => new Energy((_value * 1055.05585262) * 1e9d, EnergyUnit.Joule), + (EnergyUnit.GigaelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176565e-19) * 1e9d, EnergyUnit.Joule), + (EnergyUnit.Gigajoule, EnergyUnit.Joule) => new Energy((_value) * 1e9d, EnergyUnit.Joule), + (EnergyUnit.GigawattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e9d, EnergyUnit.Joule), + (EnergyUnit.GigawattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e9d, EnergyUnit.Joule), + (EnergyUnit.HorsepowerHour, EnergyUnit.Joule) => new Energy(_value * 2.6845195377e6, EnergyUnit.Joule), + (EnergyUnit.KilobritishThermalUnit, EnergyUnit.Joule) => new Energy((_value * 1055.05585262) * 1e3d, EnergyUnit.Joule), + (EnergyUnit.Kilocalorie, EnergyUnit.Joule) => new Energy((_value * 4.184) * 1e3d, EnergyUnit.Joule), + (EnergyUnit.KiloelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176565e-19) * 1e3d, EnergyUnit.Joule), + (EnergyUnit.Kilojoule, EnergyUnit.Joule) => new Energy((_value) * 1e3d, EnergyUnit.Joule), + (EnergyUnit.KilowattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e3d, EnergyUnit.Joule), + (EnergyUnit.KilowattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e3d, EnergyUnit.Joule), + (EnergyUnit.MegabritishThermalUnit, EnergyUnit.Joule) => new Energy((_value * 1055.05585262) * 1e6d, EnergyUnit.Joule), + (EnergyUnit.Megacalorie, EnergyUnit.Joule) => new Energy((_value * 4.184) * 1e6d, EnergyUnit.Joule), + (EnergyUnit.MegaelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176565e-19) * 1e6d, EnergyUnit.Joule), + (EnergyUnit.Megajoule, EnergyUnit.Joule) => new Energy((_value) * 1e6d, EnergyUnit.Joule), + (EnergyUnit.MegawattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e6d, EnergyUnit.Joule), + (EnergyUnit.MegawattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e6d, EnergyUnit.Joule), + (EnergyUnit.Millijoule, EnergyUnit.Joule) => new Energy((_value) * 1e-3d, EnergyUnit.Joule), + (EnergyUnit.Petajoule, EnergyUnit.Joule) => new Energy((_value) * 1e15d, EnergyUnit.Joule), + (EnergyUnit.TeraelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176565e-19) * 1e12d, EnergyUnit.Joule), + (EnergyUnit.Terajoule, EnergyUnit.Joule) => new Energy((_value) * 1e12d, EnergyUnit.Joule), + (EnergyUnit.TerawattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e12d, EnergyUnit.Joule), + (EnergyUnit.TerawattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e12d, EnergyUnit.Joule), + (EnergyUnit.ThermEc, EnergyUnit.Joule) => new Energy(_value * 1.05505585262e8, EnergyUnit.Joule), + (EnergyUnit.ThermImperial, EnergyUnit.Joule) => new Energy(_value * 1.05505585257348e8, EnergyUnit.Joule), + (EnergyUnit.ThermUs, EnergyUnit.Joule) => new Energy(_value * 1.054804e8, EnergyUnit.Joule), + (EnergyUnit.WattDay, EnergyUnit.Joule) => new Energy(_value * 24 * 3600d, EnergyUnit.Joule), + (EnergyUnit.WattHour, EnergyUnit.Joule) => new Energy(_value * 3600d, EnergyUnit.Joule), + + // BaseUnit -> EnergyUnit + (EnergyUnit.Joule, EnergyUnit.BritishThermalUnit) => new Energy(_value / 1055.05585262, EnergyUnit.BritishThermalUnit), + (EnergyUnit.Joule, EnergyUnit.Calorie) => new Energy(_value / 4.184, EnergyUnit.Calorie), + (EnergyUnit.Joule, EnergyUnit.DecathermEc) => new Energy((_value / 1.05505585262e8) / 1e1d, EnergyUnit.DecathermEc), + (EnergyUnit.Joule, EnergyUnit.DecathermImperial) => new Energy((_value / 1.05505585257348e8) / 1e1d, EnergyUnit.DecathermImperial), + (EnergyUnit.Joule, EnergyUnit.DecathermUs) => new Energy((_value / 1.054804e8) / 1e1d, EnergyUnit.DecathermUs), + (EnergyUnit.Joule, EnergyUnit.ElectronVolt) => new Energy(_value / 1.602176565e-19, EnergyUnit.ElectronVolt), + (EnergyUnit.Joule, EnergyUnit.Erg) => new Energy(_value / 1e-7, EnergyUnit.Erg), + (EnergyUnit.Joule, EnergyUnit.FootPound) => new Energy(_value / 1.355817948, EnergyUnit.FootPound), + (EnergyUnit.Joule, EnergyUnit.GigabritishThermalUnit) => new Energy((_value / 1055.05585262) / 1e9d, EnergyUnit.GigabritishThermalUnit), + (EnergyUnit.Joule, EnergyUnit.GigaelectronVolt) => new Energy((_value / 1.602176565e-19) / 1e9d, EnergyUnit.GigaelectronVolt), + (EnergyUnit.Joule, EnergyUnit.Gigajoule) => new Energy((_value) / 1e9d, EnergyUnit.Gigajoule), + (EnergyUnit.Joule, EnergyUnit.GigawattDay) => new Energy((_value / (24 * 3600d)) / 1e9d, EnergyUnit.GigawattDay), + (EnergyUnit.Joule, EnergyUnit.GigawattHour) => new Energy((_value / 3600d) / 1e9d, EnergyUnit.GigawattHour), + (EnergyUnit.Joule, EnergyUnit.HorsepowerHour) => new Energy(_value / 2.6845195377e6, EnergyUnit.HorsepowerHour), + (EnergyUnit.Joule, EnergyUnit.KilobritishThermalUnit) => new Energy((_value / 1055.05585262) / 1e3d, EnergyUnit.KilobritishThermalUnit), + (EnergyUnit.Joule, EnergyUnit.Kilocalorie) => new Energy((_value / 4.184) / 1e3d, EnergyUnit.Kilocalorie), + (EnergyUnit.Joule, EnergyUnit.KiloelectronVolt) => new Energy((_value / 1.602176565e-19) / 1e3d, EnergyUnit.KiloelectronVolt), + (EnergyUnit.Joule, EnergyUnit.Kilojoule) => new Energy((_value) / 1e3d, EnergyUnit.Kilojoule), + (EnergyUnit.Joule, EnergyUnit.KilowattDay) => new Energy((_value / (24 * 3600d)) / 1e3d, EnergyUnit.KilowattDay), + (EnergyUnit.Joule, EnergyUnit.KilowattHour) => new Energy((_value / 3600d) / 1e3d, EnergyUnit.KilowattHour), + (EnergyUnit.Joule, EnergyUnit.MegabritishThermalUnit) => new Energy((_value / 1055.05585262) / 1e6d, EnergyUnit.MegabritishThermalUnit), + (EnergyUnit.Joule, EnergyUnit.Megacalorie) => new Energy((_value / 4.184) / 1e6d, EnergyUnit.Megacalorie), + (EnergyUnit.Joule, EnergyUnit.MegaelectronVolt) => new Energy((_value / 1.602176565e-19) / 1e6d, EnergyUnit.MegaelectronVolt), + (EnergyUnit.Joule, EnergyUnit.Megajoule) => new Energy((_value) / 1e6d, EnergyUnit.Megajoule), + (EnergyUnit.Joule, EnergyUnit.MegawattDay) => new Energy((_value / (24 * 3600d)) / 1e6d, EnergyUnit.MegawattDay), + (EnergyUnit.Joule, EnergyUnit.MegawattHour) => new Energy((_value / 3600d) / 1e6d, EnergyUnit.MegawattHour), + (EnergyUnit.Joule, EnergyUnit.Millijoule) => new Energy((_value) / 1e-3d, EnergyUnit.Millijoule), + (EnergyUnit.Joule, EnergyUnit.Petajoule) => new Energy((_value) / 1e15d, EnergyUnit.Petajoule), + (EnergyUnit.Joule, EnergyUnit.TeraelectronVolt) => new Energy((_value / 1.602176565e-19) / 1e12d, EnergyUnit.TeraelectronVolt), + (EnergyUnit.Joule, EnergyUnit.Terajoule) => new Energy((_value) / 1e12d, EnergyUnit.Terajoule), + (EnergyUnit.Joule, EnergyUnit.TerawattDay) => new Energy((_value / (24 * 3600d)) / 1e12d, EnergyUnit.TerawattDay), + (EnergyUnit.Joule, EnergyUnit.TerawattHour) => new Energy((_value / 3600d) / 1e12d, EnergyUnit.TerawattHour), + (EnergyUnit.Joule, EnergyUnit.ThermEc) => new Energy(_value / 1.05505585262e8, EnergyUnit.ThermEc), + (EnergyUnit.Joule, EnergyUnit.ThermImperial) => new Energy(_value / 1.05505585257348e8, EnergyUnit.ThermImperial), + (EnergyUnit.Joule, EnergyUnit.ThermUs) => new Energy(_value / 1.054804e8, EnergyUnit.ThermUs), + (EnergyUnit.Joule, EnergyUnit.WattDay) => new Energy(_value / (24 * 3600d), EnergyUnit.WattDay), + (EnergyUnit.Joule, EnergyUnit.WattHour) => new Energy(_value / 3600d, EnergyUnit.WattHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is EnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<EnergyUnit> IQuantity<EnergyUnit>.ToUnit(EnergyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<EnergyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Energy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Energy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Energy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Energy)) + return this; + else if (conversionType == typeof(EnergyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Energy.Info; + else if (conversionType == typeof(BaseDimensions)) + return Energy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Energy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Energy/EnergyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Energy/EnergyUnit.g.cs new file mode 100644 index 0000000000..2e8dd78935 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Energy/EnergyUnit.g.cs @@ -0,0 +1,69 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum EnergyUnit + { + BritishThermalUnit = 1, + Calorie = 2, + DecathermEc = 3, + DecathermImperial = 4, + DecathermUs = 5, + ElectronVolt = 6, + Erg = 7, + FootPound = 8, + GigabritishThermalUnit = 9, + GigaelectronVolt = 10, + Gigajoule = 11, + GigawattDay = 12, + GigawattHour = 13, + HorsepowerHour = 14, + Joule = 15, + KilobritishThermalUnit = 16, + Kilocalorie = 17, + KiloelectronVolt = 18, + Kilojoule = 19, + KilowattDay = 20, + KilowattHour = 21, + MegabritishThermalUnit = 22, + Megacalorie = 23, + MegaelectronVolt = 24, + Megajoule = 25, + MegawattDay = 26, + MegawattHour = 27, + Millijoule = 28, + Petajoule = 43, + TeraelectronVolt = 29, + Terajoule = 37, + TerawattDay = 30, + TerawattHour = 31, + ThermEc = 32, + ThermImperial = 33, + ThermUs = 34, + WattDay = 35, + WattHour = 36, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensity.csproj b/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensity.csproj new file mode 100644 index 0000000000..9c2c0ffedd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET EnergyDensity</Title> + <Description>Adds EnergyDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>energydensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c5025916-5039-97c2-b450-af1420f5fb08}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.EnergyDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensity.g.cs b/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensity.g.cs new file mode 100644 index 0000000000..a6094512ab --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensity.g.cs @@ -0,0 +1,1069 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + [DataContract] + public readonly partial struct EnergyDensity : IArithmeticQuantity<EnergyDensity, EnergyDensityUnit, double>, IEquatable<EnergyDensity>, IComparable, IComparable<EnergyDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly EnergyDensityUnit? _unit; + + static EnergyDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); + BaseUnit = EnergyDensityUnit.JoulePerCubicMeter; + Units = Enum.GetValues(typeof(EnergyDensityUnit)).Cast<EnergyDensityUnit>().ToArray(); + Zero = new EnergyDensity(0, BaseUnit); + Info = new QuantityInfo<EnergyDensityUnit>("EnergyDensity", + new UnitInfo<EnergyDensityUnit>[] + { + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.GigajoulePerCubicMeter, "GigajoulesPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.GigawattHourPerCubicMeter, "GigawattHoursPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.JoulePerCubicMeter, "JoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.KilojoulePerCubicMeter, "KilojoulesPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.KilowattHourPerCubicMeter, "KilowattHoursPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.MegajoulePerCubicMeter, "MegajoulesPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.MegawattHourPerCubicMeter, "MegawattHoursPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.PetajoulePerCubicMeter, "PetajoulesPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.PetawattHourPerCubicMeter, "PetawattHoursPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.TerajoulePerCubicMeter, "TerajoulesPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.TerawattHourPerCubicMeter, "TerawattHoursPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<EnergyDensityUnit>(EnergyDensityUnit.WattHourPerCubicMeter, "WattHoursPerCubicMeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public EnergyDensity(double value, EnergyDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="EnergyDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<EnergyDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of EnergyDensity, which is JoulePerCubicMeter. All conversions go via this value. + /// </summary> + public static EnergyDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the EnergyDensity quantity. + /// </summary> + public static EnergyDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerCubicMeter. + /// </summary> + public static EnergyDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static EnergyDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public EnergyDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<EnergyDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => EnergyDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.GigajoulePerCubicMeter"/> + /// </summary> + public double GigajoulesPerCubicMeter => As(EnergyDensityUnit.GigajoulePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.GigawattHourPerCubicMeter"/> + /// </summary> + public double GigawattHoursPerCubicMeter => As(EnergyDensityUnit.GigawattHourPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.JoulePerCubicMeter"/> + /// </summary> + public double JoulesPerCubicMeter => As(EnergyDensityUnit.JoulePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.KilojoulePerCubicMeter"/> + /// </summary> + public double KilojoulesPerCubicMeter => As(EnergyDensityUnit.KilojoulePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.KilowattHourPerCubicMeter"/> + /// </summary> + public double KilowattHoursPerCubicMeter => As(EnergyDensityUnit.KilowattHourPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.MegajoulePerCubicMeter"/> + /// </summary> + public double MegajoulesPerCubicMeter => As(EnergyDensityUnit.MegajoulePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.MegawattHourPerCubicMeter"/> + /// </summary> + public double MegawattHoursPerCubicMeter => As(EnergyDensityUnit.MegawattHourPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.PetajoulePerCubicMeter"/> + /// </summary> + public double PetajoulesPerCubicMeter => As(EnergyDensityUnit.PetajoulePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.PetawattHourPerCubicMeter"/> + /// </summary> + public double PetawattHoursPerCubicMeter => As(EnergyDensityUnit.PetawattHourPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.TerajoulePerCubicMeter"/> + /// </summary> + public double TerajoulesPerCubicMeter => As(EnergyDensityUnit.TerajoulePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.TerawattHourPerCubicMeter"/> + /// </summary> + public double TerawattHoursPerCubicMeter => As(EnergyDensityUnit.TerawattHourPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EnergyDensityUnit.WattHourPerCubicMeter"/> + /// </summary> + public double WattHoursPerCubicMeter => As(EnergyDensityUnit.WattHourPerCubicMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: EnergyDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.GigajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.GigawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.KilojoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.KilowattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.MegajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.MegawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.PetajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.PetawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.TerajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.TerawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.WattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> EnergyDensityUnit + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.GigajoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.GigawattHourPerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilojoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.KilojoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilowattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.KilowattHourPerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.MegajoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.MegawattHourPerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.PetajoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.PetawattHourPerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.TerajoulePerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.TerawattHourPerCubicMeter)); + unitConverter.SetConversionFunction<EnergyDensity>(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.WattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.WattHourPerCubicMeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.GigajoulePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"GJ/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.GigawattHourPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"GWh/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.JoulePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"J/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.KilojoulePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kJ/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.KilowattHourPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kWh/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.MegajoulePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"MJ/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.MegawattHourPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"MWh/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.PetajoulePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"PJ/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.PetawattHourPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"PWh/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.TerajoulePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"TJ/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.TerawattHourPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"TWh/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EnergyDensityUnit.WattHourPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"Wh/m³"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(EnergyDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(EnergyDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.GigajoulePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromGigajoulesPerCubicMeter(QuantityValue gigajoulespercubicmeter) + { + double value = (double) gigajoulespercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.GigajoulePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.GigawattHourPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromGigawattHoursPerCubicMeter(QuantityValue gigawatthourspercubicmeter) + { + double value = (double) gigawatthourspercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.GigawattHourPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.JoulePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromJoulesPerCubicMeter(QuantityValue joulespercubicmeter) + { + double value = (double) joulespercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.JoulePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.KilojoulePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromKilojoulesPerCubicMeter(QuantityValue kilojoulespercubicmeter) + { + double value = (double) kilojoulespercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.KilojoulePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.KilowattHourPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromKilowattHoursPerCubicMeter(QuantityValue kilowatthourspercubicmeter) + { + double value = (double) kilowatthourspercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.KilowattHourPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.MegajoulePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromMegajoulesPerCubicMeter(QuantityValue megajoulespercubicmeter) + { + double value = (double) megajoulespercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.MegajoulePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.MegawattHourPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromMegawattHoursPerCubicMeter(QuantityValue megawatthourspercubicmeter) + { + double value = (double) megawatthourspercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.MegawattHourPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.PetajoulePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromPetajoulesPerCubicMeter(QuantityValue petajoulespercubicmeter) + { + double value = (double) petajoulespercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.PetajoulePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.PetawattHourPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromPetawattHoursPerCubicMeter(QuantityValue petawatthourspercubicmeter) + { + double value = (double) petawatthourspercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.PetawattHourPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.TerajoulePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromTerajoulesPerCubicMeter(QuantityValue terajoulespercubicmeter) + { + double value = (double) terajoulespercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.TerajoulePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.TerawattHourPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromTerawattHoursPerCubicMeter(QuantityValue terawatthourspercubicmeter) + { + double value = (double) terawatthourspercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.TerawattHourPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="EnergyDensity"/> from <see cref="EnergyDensityUnit.WattHourPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static EnergyDensity FromWattHoursPerCubicMeter(QuantityValue watthourspercubicmeter) + { + double value = (double) watthourspercubicmeter; + return new EnergyDensity(value, EnergyDensityUnit.WattHourPerCubicMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="EnergyDensityUnit" /> to <see cref="EnergyDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>EnergyDensity unit value.</returns> + public static EnergyDensity From(QuantityValue value, EnergyDensityUnit fromUnit) + { + return new EnergyDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static EnergyDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static EnergyDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<EnergyDensity, EnergyDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out EnergyDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out EnergyDensity result) + { + return QuantityParser.Default.TryParse<EnergyDensity, EnergyDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static EnergyDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static EnergyDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<EnergyDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.EnergyDensityUnit)"/> + public static bool TryParseUnit(string str, out EnergyDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out EnergyDensityUnit unit) + { + return UnitParser.Default.TryParse<EnergyDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static EnergyDensity operator -(EnergyDensity right) + { + return new EnergyDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="EnergyDensity"/> from adding two <see cref="EnergyDensity"/>.</summary> + public static EnergyDensity operator +(EnergyDensity left, EnergyDensity right) + { + return new EnergyDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="EnergyDensity"/> from subtracting two <see cref="EnergyDensity"/>.</summary> + public static EnergyDensity operator -(EnergyDensity left, EnergyDensity right) + { + return new EnergyDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="EnergyDensity"/> from multiplying value and <see cref="EnergyDensity"/>.</summary> + public static EnergyDensity operator *(double left, EnergyDensity right) + { + return new EnergyDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="EnergyDensity"/> from multiplying value and <see cref="EnergyDensity"/>.</summary> + public static EnergyDensity operator *(EnergyDensity left, double right) + { + return new EnergyDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="EnergyDensity"/> from dividing <see cref="EnergyDensity"/> by value.</summary> + public static EnergyDensity operator /(EnergyDensity left, double right) + { + return new EnergyDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="EnergyDensity"/> by <see cref="EnergyDensity"/>.</summary> + public static double operator /(EnergyDensity left, EnergyDensity right) + { + return left.JoulesPerCubicMeter / right.JoulesPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(EnergyDensity left, EnergyDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(EnergyDensity left, EnergyDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(EnergyDensity left, EnergyDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(EnergyDensity left, EnergyDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="EnergyDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(EnergyDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(EnergyDensity left, EnergyDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="EnergyDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(EnergyDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(EnergyDensity left, EnergyDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="EnergyDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(EnergyDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is EnergyDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="EnergyDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(EnergyDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(EnergyDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="EnergyDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is EnergyDensity otherQuantity)) throw new ArgumentException("Expected type EnergyDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="EnergyDensity"/> with another <see cref="EnergyDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(EnergyDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another EnergyDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(EnergyDensity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current EnergyDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(EnergyDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is EnergyDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this EnergyDensity to another EnergyDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A EnergyDensity with the specified unit.</returns> + public EnergyDensity ToUnit(EnergyDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="EnergyDensity"/> to another <see cref="EnergyDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A EnergyDensity with the specified unit.</returns> + public EnergyDensity ToUnit(EnergyDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(EnergyDensity), Unit, typeof(EnergyDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (EnergyDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="EnergyDensity"/> to another <see cref="EnergyDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="EnergyDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(EnergyDensityUnit unit, [NotNullWhen(true)] out EnergyDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + EnergyDensity? convertedOrNull = (Unit, unit) switch + { + // EnergyDensityUnit -> BaseUnit + (EnergyDensityUnit.GigajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e9d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.GigawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e9d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.KilojoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e3d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.KilowattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e3d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.MegajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e6d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.MegawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e6d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.PetajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e15d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.PetawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e15d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.TerajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e12d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.TerawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e12d, EnergyDensityUnit.JoulePerCubicMeter), + (EnergyDensityUnit.WattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity(_value * 3.6e+3, EnergyDensityUnit.JoulePerCubicMeter), + + // BaseUnit -> EnergyDensityUnit + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigajoulePerCubicMeter) => new EnergyDensity((_value) / 1e9d, EnergyDensityUnit.GigajoulePerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e9d, EnergyDensityUnit.GigawattHourPerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilojoulePerCubicMeter) => new EnergyDensity((_value) / 1e3d, EnergyDensityUnit.KilojoulePerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilowattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e3d, EnergyDensityUnit.KilowattHourPerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegajoulePerCubicMeter) => new EnergyDensity((_value) / 1e6d, EnergyDensityUnit.MegajoulePerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e6d, EnergyDensityUnit.MegawattHourPerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetajoulePerCubicMeter) => new EnergyDensity((_value) / 1e15d, EnergyDensityUnit.PetajoulePerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e15d, EnergyDensityUnit.PetawattHourPerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerajoulePerCubicMeter) => new EnergyDensity((_value) / 1e12d, EnergyDensityUnit.TerajoulePerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e12d, EnergyDensityUnit.TerawattHourPerCubicMeter), + (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.WattHourPerCubicMeter) => new EnergyDensity(_value / 3.6e+3, EnergyDensityUnit.WattHourPerCubicMeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is EnergyDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<EnergyDensityUnit> IQuantity<EnergyDensityUnit>.ToUnit(EnergyDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<EnergyDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(EnergyDensity)) + return this; + else if (conversionType == typeof(EnergyDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return EnergyDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return EnergyDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensityUnit.g.cs new file mode 100644 index 0000000000..bf72f7d4f3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/EnergyDensity/EnergyDensityUnit.g.cs @@ -0,0 +1,43 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum EnergyDensityUnit + { + GigajoulePerCubicMeter = 6, + GigawattHourPerCubicMeter = 8, + JoulePerCubicMeter = 3, + KilojoulePerCubicMeter = 5, + KilowattHourPerCubicMeter = 2, + MegajoulePerCubicMeter = 9, + MegawattHourPerCubicMeter = 7, + PetajoulePerCubicMeter = 4, + PetawattHourPerCubicMeter = 1, + TerajoulePerCubicMeter = 10, + TerawattHourPerCubicMeter = 12, + WattHourPerCubicMeter = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Entropy/Entropy.csproj b/UnitsNet.Modular/GeneratedCode/Entropy/Entropy.csproj new file mode 100644 index 0000000000..cfdda9ce15 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Entropy/Entropy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Entropy</Title> + <Description>Adds Entropy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>entropy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{816884bb-a5f6-5c07-967b-bb8f21d724b7}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Entropy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Entropy/Entropy.g.cs b/UnitsNet.Modular/GeneratedCode/Entropy/Entropy.g.cs new file mode 100644 index 0000000000..99012b79e6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Entropy/Entropy.g.cs @@ -0,0 +1,964 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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 + /// </summary> + [DataContract] + public readonly partial struct Entropy : IArithmeticQuantity<Entropy, EntropyUnit, double>, IEquatable<Entropy>, IComparable, IComparable<Entropy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly EntropyUnit? _unit; + + static Entropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); + BaseUnit = EntropyUnit.JoulePerKelvin; + Units = Enum.GetValues(typeof(EntropyUnit)).Cast<EntropyUnit>().ToArray(); + Zero = new Entropy(0, BaseUnit); + Info = new QuantityInfo<EntropyUnit>("Entropy", + new UnitInfo<EntropyUnit>[] + { + new UnitInfo<EntropyUnit>(EntropyUnit.CaloriePerKelvin, "CaloriesPerKelvin", BaseUnits.Undefined), + new UnitInfo<EntropyUnit>(EntropyUnit.JoulePerDegreeCelsius, "JoulesPerDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<EntropyUnit>(EntropyUnit.JoulePerKelvin, "JoulesPerKelvin", BaseUnits.Undefined), + new UnitInfo<EntropyUnit>(EntropyUnit.KilocaloriePerKelvin, "KilocaloriesPerKelvin", BaseUnits.Undefined), + new UnitInfo<EntropyUnit>(EntropyUnit.KilojoulePerDegreeCelsius, "KilojoulesPerDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<EntropyUnit>(EntropyUnit.KilojoulePerKelvin, "KilojoulesPerKelvin", BaseUnits.Undefined), + new UnitInfo<EntropyUnit>(EntropyUnit.MegajoulePerKelvin, "MegajoulesPerKelvin", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Entropy(double value, EntropyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Entropy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<EntropyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. + /// </summary> + public static EntropyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Entropy quantity. + /// </summary> + public static EntropyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. + /// </summary> + public static Entropy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Entropy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<EntropyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Entropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.CaloriePerKelvin"/> + /// </summary> + public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.JoulePerDegreeCelsius"/> + /// </summary> + public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.JoulePerKelvin"/> + /// </summary> + public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.KilocaloriePerKelvin"/> + /// </summary> + public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.KilojoulePerDegreeCelsius"/> + /// </summary> + public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.KilojoulePerKelvin"/> + /// </summary> + public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="EntropyUnit.MegajoulePerKelvin"/> + /// </summary> + public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: EntropyUnit -> BaseUnit + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.CaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.KilocaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.KilojoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.KilojoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.MegajoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> EntropyUnit + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.CaloriePerKelvin, quantity => quantity.ToUnit(EntropyUnit.CaloriePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerDegreeCelsius, quantity => quantity.ToUnit(EntropyUnit.JoulePerDegreeCelsius)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.KilocaloriePerKelvin, quantity => quantity.ToUnit(EntropyUnit.KilocaloriePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerDegreeCelsius, quantity => quantity.ToUnit(EntropyUnit.KilojoulePerDegreeCelsius)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.KilojoulePerKelvin)); + unitConverter.SetConversionFunction<Entropy>(EntropyUnit.JoulePerKelvin, EntropyUnit.MegajoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.MegajoulePerKelvin)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.CaloriePerKelvin, new CultureInfo("en-US"), false, true, new string[]{"cal/K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.JoulePerDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"J/C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.JoulePerKelvin, new CultureInfo("en-US"), false, true, new string[]{"J/K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.KilocaloriePerKelvin, new CultureInfo("en-US"), false, true, new string[]{"kcal/K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.KilojoulePerDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"kJ/C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.KilojoulePerKelvin, new CultureInfo("en-US"), false, true, new string[]{"kJ/K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(EntropyUnit.MegajoulePerKelvin, new CultureInfo("en-US"), false, true, new string[]{"MJ/K"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(EntropyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(EntropyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.CaloriePerKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) + { + double value = (double) caloriesperkelvin; + return new Entropy(value, EntropyUnit.CaloriePerKelvin); + } + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.JoulePerDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) + { + double value = (double) joulesperdegreecelsius; + return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.JoulePerKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) + { + double value = (double) joulesperkelvin; + return new Entropy(value, EntropyUnit.JoulePerKelvin); + } + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.KilocaloriePerKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) + { + double value = (double) kilocaloriesperkelvin; + return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); + } + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.KilojoulePerDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) + { + double value = (double) kilojoulesperdegreecelsius; + return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.KilojoulePerKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) + { + double value = (double) kilojoulesperkelvin; + return new Entropy(value, EntropyUnit.KilojoulePerKelvin); + } + + /// <summary> + /// Creates a <see cref="Entropy"/> from <see cref="EntropyUnit.MegajoulePerKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) + { + double value = (double) megajoulesperkelvin; + return new Entropy(value, EntropyUnit.MegajoulePerKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="EntropyUnit" /> to <see cref="Entropy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Entropy unit value.</returns> + public static Entropy From(QuantityValue value, EntropyUnit fromUnit) + { + return new Entropy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Entropy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Entropy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Entropy, EntropyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Entropy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Entropy result) + { + return QuantityParser.Default.TryParse<Entropy, EntropyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static EntropyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static EntropyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<EntropyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.EntropyUnit)"/> + public static bool TryParseUnit(string str, out EntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out EntropyUnit unit) + { + return UnitParser.Default.TryParse<EntropyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Entropy operator -(Entropy right) + { + return new Entropy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Entropy"/> from adding two <see cref="Entropy"/>.</summary> + public static Entropy operator +(Entropy left, Entropy right) + { + return new Entropy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Entropy"/> from subtracting two <see cref="Entropy"/>.</summary> + public static Entropy operator -(Entropy left, Entropy right) + { + return new Entropy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Entropy"/> from multiplying value and <see cref="Entropy"/>.</summary> + public static Entropy operator *(double left, Entropy right) + { + return new Entropy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Entropy"/> from multiplying value and <see cref="Entropy"/>.</summary> + public static Entropy operator *(Entropy left, double right) + { + return new Entropy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Entropy"/> from dividing <see cref="Entropy"/> by value.</summary> + public static Entropy operator /(Entropy left, double right) + { + return new Entropy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Entropy"/> by <see cref="Entropy"/>.</summary> + public static double operator /(Entropy left, Entropy right) + { + return left.JoulesPerKelvin / right.JoulesPerKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Entropy left, Entropy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Entropy left, Entropy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Entropy left, Entropy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Entropy left, Entropy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Entropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Entropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Entropy left, Entropy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Entropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Entropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Entropy left, Entropy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Entropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Entropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Entropy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Entropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Entropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Entropy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Entropy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Entropy otherQuantity)) throw new ArgumentException("Expected type Entropy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Entropy"/> with another <see cref="Entropy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Entropy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Entropy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Entropy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(EntropyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is EntropyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Entropy to another Entropy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Entropy with the specified unit.</returns> + public Entropy ToUnit(EntropyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Entropy"/> to another <see cref="Entropy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Entropy with the specified unit.</returns> + public Entropy ToUnit(EntropyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Entropy), Unit, typeof(Entropy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Entropy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Entropy"/> to another <see cref="Entropy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Entropy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(EntropyUnit unit, [NotNullWhen(true)] out Entropy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Entropy? convertedOrNull = (Unit, unit) switch + { + // EntropyUnit -> BaseUnit + (EntropyUnit.CaloriePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy(_value * 4.184, EntropyUnit.JoulePerKelvin), + (EntropyUnit.JoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin) => new Entropy(_value, EntropyUnit.JoulePerKelvin), + (EntropyUnit.KilocaloriePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy((_value * 4.184) * 1e3d, EntropyUnit.JoulePerKelvin), + (EntropyUnit.KilojoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin) => new Entropy((_value) * 1e3d, EntropyUnit.JoulePerKelvin), + (EntropyUnit.KilojoulePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy((_value) * 1e3d, EntropyUnit.JoulePerKelvin), + (EntropyUnit.MegajoulePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy((_value) * 1e6d, EntropyUnit.JoulePerKelvin), + + // BaseUnit -> EntropyUnit + (EntropyUnit.JoulePerKelvin, EntropyUnit.CaloriePerKelvin) => new Entropy(_value / 4.184, EntropyUnit.CaloriePerKelvin), + (EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerDegreeCelsius) => new Entropy(_value, EntropyUnit.JoulePerDegreeCelsius), + (EntropyUnit.JoulePerKelvin, EntropyUnit.KilocaloriePerKelvin) => new Entropy((_value / 4.184) / 1e3d, EntropyUnit.KilocaloriePerKelvin), + (EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerDegreeCelsius) => new Entropy((_value) / 1e3d, EntropyUnit.KilojoulePerDegreeCelsius), + (EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerKelvin) => new Entropy((_value) / 1e3d, EntropyUnit.KilojoulePerKelvin), + (EntropyUnit.JoulePerKelvin, EntropyUnit.MegajoulePerKelvin) => new Entropy((_value) / 1e6d, EntropyUnit.MegajoulePerKelvin), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is EntropyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<EntropyUnit> IQuantity<EntropyUnit>.ToUnit(EntropyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<EntropyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Entropy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Entropy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Entropy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Entropy)) + return this; + else if (conversionType == typeof(EntropyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Entropy.Info; + else if (conversionType == typeof(BaseDimensions)) + return Entropy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Entropy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Entropy/EntropyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Entropy/EntropyUnit.g.cs new file mode 100644 index 0000000000..1fbd647e03 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Entropy/EntropyUnit.g.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum EntropyUnit + { + CaloriePerKelvin = 1, + JoulePerDegreeCelsius = 2, + JoulePerKelvin = 3, + KilocaloriePerKelvin = 4, + KilojoulePerDegreeCelsius = 5, + KilojoulePerKelvin = 6, + MegajoulePerKelvin = 7, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Force/Force.csproj b/UnitsNet.Modular/GeneratedCode/Force/Force.csproj new file mode 100644 index 0000000000..7b8908fd15 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Force/Force.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Force</Title> + <Description>Adds Force units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>force unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5517dacf-b1ff-6515-e5b6-b5081f92f407}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Force</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Force/Force.g.cs b/UnitsNet.Modular/GeneratedCode/Force/Force.g.cs new file mode 100644 index 0000000000..1d2d399d1e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Force/Force.g.cs @@ -0,0 +1,1145 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Force : IArithmeticQuantity<Force, ForceUnit, double>, IEquatable<Force>, IComparable, IComparable<Force>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ForceUnit? _unit; + + static Force() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + BaseUnit = ForceUnit.Newton; + Units = Enum.GetValues(typeof(ForceUnit)).Cast<ForceUnit>().ToArray(); + Zero = new Force(0, BaseUnit); + Info = new QuantityInfo<ForceUnit>("Force", + new UnitInfo<ForceUnit>[] + { + new UnitInfo<ForceUnit>(ForceUnit.Decanewton, "Decanewtons", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Dyn, "Dyne", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second)), + new UnitInfo<ForceUnit>(ForceUnit.KilogramForce, "KilogramsForce", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Kilonewton, "Kilonewtons", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.KiloPond, "KiloPonds", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.KilopoundForce, "KilopoundsForce", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Meganewton, "Meganewtons", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Micronewton, "Micronewtons", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Millinewton, "Millinewtons", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Newton, "Newtons", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), + new UnitInfo<ForceUnit>(ForceUnit.OunceForce, "OunceForce", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.Poundal, "Poundals", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound, time: DurationUnit.Second)), + new UnitInfo<ForceUnit>(ForceUnit.PoundForce, "PoundsForce", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.ShortTonForce, "ShortTonsForce", BaseUnits.Undefined), + new UnitInfo<ForceUnit>(ForceUnit.TonneForce, "TonnesForce", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Force(double value, ForceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Force" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ForceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Force, which is Newton. All conversions go via this value. + /// </summary> + public static ForceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Force quantity. + /// </summary> + public static ForceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Newton. + /// </summary> + public static Force Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Force AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ForceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Force.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Decanewton"/> + /// </summary> + public double Decanewtons => As(ForceUnit.Decanewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Dyn"/> + /// </summary> + public double Dyne => As(ForceUnit.Dyn); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.KilogramForce"/> + /// </summary> + public double KilogramsForce => As(ForceUnit.KilogramForce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Kilonewton"/> + /// </summary> + public double Kilonewtons => As(ForceUnit.Kilonewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.KiloPond"/> + /// </summary> + public double KiloPonds => As(ForceUnit.KiloPond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.KilopoundForce"/> + /// </summary> + public double KilopoundsForce => As(ForceUnit.KilopoundForce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Meganewton"/> + /// </summary> + public double Meganewtons => As(ForceUnit.Meganewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Micronewton"/> + /// </summary> + public double Micronewtons => As(ForceUnit.Micronewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Millinewton"/> + /// </summary> + public double Millinewtons => As(ForceUnit.Millinewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Newton"/> + /// </summary> + public double Newtons => As(ForceUnit.Newton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.OunceForce"/> + /// </summary> + public double OunceForce => As(ForceUnit.OunceForce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.Poundal"/> + /// </summary> + public double Poundals => As(ForceUnit.Poundal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.PoundForce"/> + /// </summary> + public double PoundsForce => As(ForceUnit.PoundForce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.ShortTonForce"/> + /// </summary> + public double ShortTonsForce => As(ForceUnit.ShortTonForce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceUnit.TonneForce"/> + /// </summary> + public double TonnesForce => As(ForceUnit.TonneForce); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ForceUnit -> BaseUnit + unitConverter.SetConversionFunction<Force>(ForceUnit.Decanewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Dyn, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.KilogramForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Kilonewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.KiloPond, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.KilopoundForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Meganewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Micronewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Millinewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.OunceForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Poundal, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.PoundForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.ShortTonForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.TonneForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Newton, quantity => quantity); + + // Register in unit converter: BaseUnit -> ForceUnit + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Decanewton, quantity => quantity.ToUnit(ForceUnit.Decanewton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Dyn, quantity => quantity.ToUnit(ForceUnit.Dyn)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.KilogramForce, quantity => quantity.ToUnit(ForceUnit.KilogramForce)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Kilonewton, quantity => quantity.ToUnit(ForceUnit.Kilonewton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.KiloPond, quantity => quantity.ToUnit(ForceUnit.KiloPond)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.KilopoundForce, quantity => quantity.ToUnit(ForceUnit.KilopoundForce)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Meganewton, quantity => quantity.ToUnit(ForceUnit.Meganewton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Micronewton, quantity => quantity.ToUnit(ForceUnit.Micronewton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Millinewton, quantity => quantity.ToUnit(ForceUnit.Millinewton)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.OunceForce, quantity => quantity.ToUnit(ForceUnit.OunceForce)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.Poundal, quantity => quantity.ToUnit(ForceUnit.Poundal)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.PoundForce, quantity => quantity.ToUnit(ForceUnit.PoundForce)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.ShortTonForce, quantity => quantity.ToUnit(ForceUnit.ShortTonForce)); + unitConverter.SetConversionFunction<Force>(ForceUnit.Newton, ForceUnit.TonneForce, quantity => quantity.ToUnit(ForceUnit.TonneForce)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Decanewton, new CultureInfo("en-US"), false, true, new string[]{"daN"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Decanewton, new CultureInfo("ru-RU"), false, true, new string[]{"даН"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Dyn, new CultureInfo("en-US"), false, true, new string[]{"dyn"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Dyn, new CultureInfo("ru-RU"), false, true, new string[]{"дин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.KilogramForce, new CultureInfo("en-US"), false, true, new string[]{"kgf"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.KilogramForce, new CultureInfo("ru-RU"), false, true, new string[]{"кгс"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Kilonewton, new CultureInfo("en-US"), false, true, new string[]{"kN"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Kilonewton, new CultureInfo("ru-RU"), false, true, new string[]{"кН"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.KiloPond, new CultureInfo("en-US"), false, true, new string[]{"kp"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.KiloPond, new CultureInfo("ru-RU"), false, true, new string[]{"кгс"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.KilopoundForce, new CultureInfo("en-US"), false, true, new string[]{"kipf", "kip", "k"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.KilopoundForce, new CultureInfo("ru-RU"), false, true, new string[]{"кипф", "койка", "К"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Meganewton, new CultureInfo("en-US"), false, true, new string[]{"MN"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Meganewton, new CultureInfo("ru-RU"), false, true, new string[]{"МН"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Micronewton, new CultureInfo("en-US"), false, true, new string[]{"µN"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Micronewton, new CultureInfo("ru-RU"), false, true, new string[]{"мкН"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Millinewton, new CultureInfo("en-US"), false, true, new string[]{"mN"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Millinewton, new CultureInfo("ru-RU"), false, true, new string[]{"мН"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Newton, new CultureInfo("en-US"), false, true, new string[]{"N"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Newton, new CultureInfo("ru-RU"), false, true, new string[]{"Н"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.OunceForce, new CultureInfo("en-US"), false, true, new string[]{"ozf"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Poundal, new CultureInfo("en-US"), false, true, new string[]{"pdl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.Poundal, new CultureInfo("ru-RU"), false, true, new string[]{"паундаль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.PoundForce, new CultureInfo("en-US"), false, true, new string[]{"lbf"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.PoundForce, new CultureInfo("ru-RU"), false, true, new string[]{"фунт-сила"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.ShortTonForce, new CultureInfo("en-US"), false, true, new string[]{"tf (short)", "t (US)f", "short tons-force"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.TonneForce, new CultureInfo("en-US"), false, true, new string[]{"tf", "Ton"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceUnit.TonneForce, new CultureInfo("ru-RU"), false, true, new string[]{"тс"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ForceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ForceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Decanewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromDecanewtons(QuantityValue decanewtons) + { + double value = (double) decanewtons; + return new Force(value, ForceUnit.Decanewton); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Dyn"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromDyne(QuantityValue dyne) + { + double value = (double) dyne; + return new Force(value, ForceUnit.Dyn); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.KilogramForce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromKilogramsForce(QuantityValue kilogramsforce) + { + double value = (double) kilogramsforce; + return new Force(value, ForceUnit.KilogramForce); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Kilonewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromKilonewtons(QuantityValue kilonewtons) + { + double value = (double) kilonewtons; + return new Force(value, ForceUnit.Kilonewton); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.KiloPond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromKiloPonds(QuantityValue kiloponds) + { + double value = (double) kiloponds; + return new Force(value, ForceUnit.KiloPond); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.KilopoundForce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromKilopoundsForce(QuantityValue kilopoundsforce) + { + double value = (double) kilopoundsforce; + return new Force(value, ForceUnit.KilopoundForce); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Meganewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromMeganewtons(QuantityValue meganewtons) + { + double value = (double) meganewtons; + return new Force(value, ForceUnit.Meganewton); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Micronewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromMicronewtons(QuantityValue micronewtons) + { + double value = (double) micronewtons; + return new Force(value, ForceUnit.Micronewton); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Millinewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromMillinewtons(QuantityValue millinewtons) + { + double value = (double) millinewtons; + return new Force(value, ForceUnit.Millinewton); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Newton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromNewtons(QuantityValue newtons) + { + double value = (double) newtons; + return new Force(value, ForceUnit.Newton); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.OunceForce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromOunceForce(QuantityValue ounceforce) + { + double value = (double) ounceforce; + return new Force(value, ForceUnit.OunceForce); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.Poundal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromPoundals(QuantityValue poundals) + { + double value = (double) poundals; + return new Force(value, ForceUnit.Poundal); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.PoundForce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromPoundsForce(QuantityValue poundsforce) + { + double value = (double) poundsforce; + return new Force(value, ForceUnit.PoundForce); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.ShortTonForce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromShortTonsForce(QuantityValue shorttonsforce) + { + double value = (double) shorttonsforce; + return new Force(value, ForceUnit.ShortTonForce); + } + + /// <summary> + /// Creates a <see cref="Force"/> from <see cref="ForceUnit.TonneForce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Force FromTonnesForce(QuantityValue tonnesforce) + { + double value = (double) tonnesforce; + return new Force(value, ForceUnit.TonneForce); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ForceUnit" /> to <see cref="Force" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Force unit value.</returns> + public static Force From(QuantityValue value, ForceUnit fromUnit) + { + return new Force((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Force Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Force Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Force, ForceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Force result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Force result) + { + return QuantityParser.Default.TryParse<Force, ForceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ForceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ForceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ForceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ForceUnit)"/> + public static bool TryParseUnit(string str, out ForceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ForceUnit unit) + { + return UnitParser.Default.TryParse<ForceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Force operator -(Force right) + { + return new Force(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Force"/> from adding two <see cref="Force"/>.</summary> + public static Force operator +(Force left, Force right) + { + return new Force(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Force"/> from subtracting two <see cref="Force"/>.</summary> + public static Force operator -(Force left, Force right) + { + return new Force(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Force"/> from multiplying value and <see cref="Force"/>.</summary> + public static Force operator *(double left, Force right) + { + return new Force(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Force"/> from multiplying value and <see cref="Force"/>.</summary> + public static Force operator *(Force left, double right) + { + return new Force(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Force"/> from dividing <see cref="Force"/> by value.</summary> + public static Force operator /(Force left, double right) + { + return new Force(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Force"/> by <see cref="Force"/>.</summary> + public static double operator /(Force left, Force right) + { + return left.Newtons / right.Newtons; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Force left, Force right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Force left, Force right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Force left, Force right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Force left, Force right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Force"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Force, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Force left, Force right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Force"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Force, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Force left, Force right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Force"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Force, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Force otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Force"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Force, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Force other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Force"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Force otherQuantity)) throw new ArgumentException("Expected type Force.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Force"/> with another <see cref="Force"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Force other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Force within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Force.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ForceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ForceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Force to another Force with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Force with the specified unit.</returns> + public Force ToUnit(ForceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Force"/> to another <see cref="Force"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Force with the specified unit.</returns> + public Force ToUnit(ForceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Force), Unit, typeof(Force), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Force)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Force"/> to another <see cref="Force"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Force"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ForceUnit unit, [NotNullWhen(true)] out Force? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Force? convertedOrNull = (Unit, unit) switch + { + // ForceUnit -> BaseUnit + (ForceUnit.Decanewton, ForceUnit.Newton) => new Force((_value) * 1e1d, ForceUnit.Newton), + (ForceUnit.Dyn, ForceUnit.Newton) => new Force(_value / 1e5, ForceUnit.Newton), + (ForceUnit.KilogramForce, ForceUnit.Newton) => new Force(_value * 9.80665002864, ForceUnit.Newton), + (ForceUnit.Kilonewton, ForceUnit.Newton) => new Force((_value) * 1e3d, ForceUnit.Newton), + (ForceUnit.KiloPond, ForceUnit.Newton) => new Force(_value * 9.80665002864, ForceUnit.Newton), + (ForceUnit.KilopoundForce, ForceUnit.Newton) => new Force((_value * 4.4482216152605095551842641431421) * 1e3d, ForceUnit.Newton), + (ForceUnit.Meganewton, ForceUnit.Newton) => new Force((_value) * 1e6d, ForceUnit.Newton), + (ForceUnit.Micronewton, ForceUnit.Newton) => new Force((_value) * 1e-6d, ForceUnit.Newton), + (ForceUnit.Millinewton, ForceUnit.Newton) => new Force((_value) * 1e-3d, ForceUnit.Newton), + (ForceUnit.OunceForce, ForceUnit.Newton) => new Force(_value * 2.780138509537812e-1, ForceUnit.Newton), + (ForceUnit.Poundal, ForceUnit.Newton) => new Force(_value * 0.13825502798973041652092282466083, ForceUnit.Newton), + (ForceUnit.PoundForce, ForceUnit.Newton) => new Force(_value * 4.4482216152605095551842641431421, ForceUnit.Newton), + (ForceUnit.ShortTonForce, ForceUnit.Newton) => new Force(_value * 8.896443230521e3, ForceUnit.Newton), + (ForceUnit.TonneForce, ForceUnit.Newton) => new Force(_value * 9.80665002864e3, ForceUnit.Newton), + + // BaseUnit -> ForceUnit + (ForceUnit.Newton, ForceUnit.Decanewton) => new Force((_value) / 1e1d, ForceUnit.Decanewton), + (ForceUnit.Newton, ForceUnit.Dyn) => new Force(_value * 1e5, ForceUnit.Dyn), + (ForceUnit.Newton, ForceUnit.KilogramForce) => new Force(_value / 9.80665002864, ForceUnit.KilogramForce), + (ForceUnit.Newton, ForceUnit.Kilonewton) => new Force((_value) / 1e3d, ForceUnit.Kilonewton), + (ForceUnit.Newton, ForceUnit.KiloPond) => new Force(_value / 9.80665002864, ForceUnit.KiloPond), + (ForceUnit.Newton, ForceUnit.KilopoundForce) => new Force((_value / 4.4482216152605095551842641431421) / 1e3d, ForceUnit.KilopoundForce), + (ForceUnit.Newton, ForceUnit.Meganewton) => new Force((_value) / 1e6d, ForceUnit.Meganewton), + (ForceUnit.Newton, ForceUnit.Micronewton) => new Force((_value) / 1e-6d, ForceUnit.Micronewton), + (ForceUnit.Newton, ForceUnit.Millinewton) => new Force((_value) / 1e-3d, ForceUnit.Millinewton), + (ForceUnit.Newton, ForceUnit.OunceForce) => new Force(_value / 2.780138509537812e-1, ForceUnit.OunceForce), + (ForceUnit.Newton, ForceUnit.Poundal) => new Force(_value / 0.13825502798973041652092282466083, ForceUnit.Poundal), + (ForceUnit.Newton, ForceUnit.PoundForce) => new Force(_value / 4.4482216152605095551842641431421, ForceUnit.PoundForce), + (ForceUnit.Newton, ForceUnit.ShortTonForce) => new Force(_value / 8.896443230521e3, ForceUnit.ShortTonForce), + (ForceUnit.Newton, ForceUnit.TonneForce) => new Force(_value / 9.80665002864e3, ForceUnit.TonneForce), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ForceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ForceUnit> IQuantity<ForceUnit>.ToUnit(ForceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ForceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Force)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Force)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Force)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Force)) + return this; + else if (conversionType == typeof(ForceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Force.Info; + else if (conversionType == typeof(BaseDimensions)) + return Force.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Force)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Force/ForceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Force/ForceUnit.g.cs new file mode 100644 index 0000000000..107e6ae7e4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Force/ForceUnit.g.cs @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ForceUnit + { + Decanewton = 1, + Dyn = 2, + KilogramForce = 3, + Kilonewton = 4, + KiloPond = 5, + KilopoundForce = 6, + Meganewton = 7, + Micronewton = 8, + Millinewton = 9, + Newton = 10, + OunceForce = 11, + Poundal = 12, + PoundForce = 13, + + /// <summary> + /// The short ton-force is a unit of force equal to 2,000 pounds-force (907.18474 kgf), that is most commonly used in the United States – known there simply as the ton or US ton. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Ton-force#Short_ton-force</remarks> + ShortTonForce = 14, + TonneForce = 15, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRate.csproj b/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRate.csproj new file mode 100644 index 0000000000..55f8f21dfe --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRate.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ForceChangeRate</Title> + <Description>Adds ForceChangeRate units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>forcechangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{97ad732d-4ce5-2027-aabc-844002d29c23}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ForceChangeRate</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRate.g.cs b/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRate.g.cs new file mode 100644 index 0000000000..f156fc90d0 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRate.g.cs @@ -0,0 +1,1132 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct ForceChangeRate : IArithmeticQuantity<ForceChangeRate, ForceChangeRateUnit, double>, IEquatable<ForceChangeRate>, IComparable, IComparable<ForceChangeRate>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ForceChangeRateUnit? _unit; + + static ForceChangeRate() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); + BaseUnit = ForceChangeRateUnit.NewtonPerSecond; + Units = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast<ForceChangeRateUnit>().ToArray(); + Zero = new ForceChangeRate(0, BaseUnit); + Info = new QuantityInfo<ForceChangeRateUnit>("ForceChangeRate", + new UnitInfo<ForceChangeRateUnit>[] + { + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.CentinewtonPerSecond, "CentinewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.DecanewtonPerMinute, "DecanewtonsPerMinute", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.DecanewtonPerSecond, "DecanewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.DecinewtonPerSecond, "DecinewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.KilonewtonPerMinute, "KilonewtonsPerMinute", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.KilonewtonPerSecond, "KilonewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.KilopoundForcePerMinute, "KilopoundsForcePerMinute", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.KilopoundForcePerSecond, "KilopoundsForcePerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.MicronewtonPerSecond, "MicronewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.MillinewtonPerSecond, "MillinewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.NanonewtonPerSecond, "NanonewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.NewtonPerMinute, "NewtonsPerMinute", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.NewtonPerSecond, "NewtonsPerSecond", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.PoundForcePerMinute, "PoundsForcePerMinute", BaseUnits.Undefined), + new UnitInfo<ForceChangeRateUnit>(ForceChangeRateUnit.PoundForcePerSecond, "PoundsForcePerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ForceChangeRate(double value, ForceChangeRateUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ForceChangeRate" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ForceChangeRateUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. + /// </summary> + public static ForceChangeRateUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ForceChangeRate quantity. + /// </summary> + public static ForceChangeRateUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. + /// </summary> + public static ForceChangeRate Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ForceChangeRate AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ForceChangeRateUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.CentinewtonPerSecond"/> + /// </summary> + public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.DecanewtonPerMinute"/> + /// </summary> + public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.DecanewtonPerSecond"/> + /// </summary> + public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.DecinewtonPerSecond"/> + /// </summary> + public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.KilonewtonPerMinute"/> + /// </summary> + public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.KilonewtonPerSecond"/> + /// </summary> + public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.KilopoundForcePerMinute"/> + /// </summary> + public double KilopoundsForcePerMinute => As(ForceChangeRateUnit.KilopoundForcePerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.KilopoundForcePerSecond"/> + /// </summary> + public double KilopoundsForcePerSecond => As(ForceChangeRateUnit.KilopoundForcePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.MicronewtonPerSecond"/> + /// </summary> + public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.MillinewtonPerSecond"/> + /// </summary> + public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.NanonewtonPerSecond"/> + /// </summary> + public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.NewtonPerMinute"/> + /// </summary> + public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.NewtonPerSecond"/> + /// </summary> + public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.PoundForcePerMinute"/> + /// </summary> + public double PoundsForcePerMinute => As(ForceChangeRateUnit.PoundForcePerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForceChangeRateUnit.PoundForcePerSecond"/> + /// </summary> + public double PoundsForcePerSecond => As(ForceChangeRateUnit.PoundForcePerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ForceChangeRateUnit -> BaseUnit + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.CentinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.DecanewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.DecanewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.DecinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.KilonewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.KilonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.KilopoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.KilopoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.MillinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NanonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.PoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.PoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> ForceChangeRateUnit + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.CentinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.CentinewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.DecanewtonPerMinute)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.DecanewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.DecinewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.KilonewtonPerMinute)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.KilonewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.KilopoundForcePerMinute)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.KilopoundForcePerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MicronewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.MicronewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MillinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.MillinewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NanonewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NanonewtonPerSecond)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerMinute)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.PoundForcePerMinute)); + unitConverter.SetConversionFunction<ForceChangeRate>(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.PoundForcePerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.CentinewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"cN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.DecanewtonPerMinute, new CultureInfo("en-US"), false, true, new string[]{"daN/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.DecanewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"daN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.DecinewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"dN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.KilonewtonPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kN/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.KilonewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.KilopoundForcePerMinute, new CultureInfo("en-US"), false, true, new string[]{"kipf/min", "kip/min", "k/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.KilopoundForcePerSecond, new CultureInfo("en-US"), false, true, new string[]{"kipf/s", "kip/s", "k/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.MicronewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.MillinewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.NanonewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"nN/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.NewtonPerMinute, new CultureInfo("en-US"), false, true, new string[]{"N/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.NewtonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"N/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.PoundForcePerMinute, new CultureInfo("en-US"), false, true, new string[]{"lbf/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForceChangeRateUnit.PoundForcePerSecond, new CultureInfo("en-US"), false, true, new string[]{"lbf/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ForceChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ForceChangeRateUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.CentinewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) + { + double value = (double) centinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.DecanewtonPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) + { + double value = (double) decanewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.DecanewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) + { + double value = (double) decanewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.DecinewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) + { + double value = (double) decinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.KilonewtonPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) + { + double value = (double) kilonewtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.KilonewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) + { + double value = (double) kilonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.KilopoundForcePerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromKilopoundsForcePerMinute(QuantityValue kilopoundsforceperminute) + { + double value = (double) kilopoundsforceperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerMinute); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.KilopoundForcePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromKilopoundsForcePerSecond(QuantityValue kilopoundsforcepersecond) + { + double value = (double) kilopoundsforcepersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.MicronewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) + { + double value = (double) micronewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.MillinewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) + { + double value = (double) millinewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.NanonewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) + { + double value = (double) nanonewtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.NewtonPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) + { + double value = (double) newtonsperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.NewtonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) + { + double value = (double) newtonspersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.PoundForcePerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromPoundsForcePerMinute(QuantityValue poundsforceperminute) + { + double value = (double) poundsforceperminute; + return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerMinute); + } + + /// <summary> + /// Creates a <see cref="ForceChangeRate"/> from <see cref="ForceChangeRateUnit.PoundForcePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForceChangeRate FromPoundsForcePerSecond(QuantityValue poundsforcepersecond) + { + double value = (double) poundsforcepersecond; + return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ForceChangeRateUnit" /> to <see cref="ForceChangeRate" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ForceChangeRate unit value.</returns> + public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) + { + return new ForceChangeRate((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ForceChangeRate Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ForceChangeRate Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ForceChangeRate, ForceChangeRateUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ForceChangeRate result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ForceChangeRate result) + { + return QuantityParser.Default.TryParse<ForceChangeRate, ForceChangeRateUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ForceChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ForceChangeRateUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ForceChangeRateUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ForceChangeRateUnit)"/> + public static bool TryParseUnit(string str, out ForceChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ForceChangeRateUnit unit) + { + return UnitParser.Default.TryParse<ForceChangeRateUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ForceChangeRate operator -(ForceChangeRate right) + { + return new ForceChangeRate(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ForceChangeRate"/> from adding two <see cref="ForceChangeRate"/>.</summary> + public static ForceChangeRate operator +(ForceChangeRate left, ForceChangeRate right) + { + return new ForceChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ForceChangeRate"/> from subtracting two <see cref="ForceChangeRate"/>.</summary> + public static ForceChangeRate operator -(ForceChangeRate left, ForceChangeRate right) + { + return new ForceChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ForceChangeRate"/> from multiplying value and <see cref="ForceChangeRate"/>.</summary> + public static ForceChangeRate operator *(double left, ForceChangeRate right) + { + return new ForceChangeRate(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ForceChangeRate"/> from multiplying value and <see cref="ForceChangeRate"/>.</summary> + public static ForceChangeRate operator *(ForceChangeRate left, double right) + { + return new ForceChangeRate(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ForceChangeRate"/> from dividing <see cref="ForceChangeRate"/> by value.</summary> + public static ForceChangeRate operator /(ForceChangeRate left, double right) + { + return new ForceChangeRate(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ForceChangeRate"/> by <see cref="ForceChangeRate"/>.</summary> + public static double operator /(ForceChangeRate left, ForceChangeRate right) + { + return left.NewtonsPerSecond / right.NewtonsPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ForceChangeRate left, ForceChangeRate right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ForceChangeRate left, ForceChangeRate right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ForceChangeRate left, ForceChangeRate right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ForceChangeRate left, ForceChangeRate right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ForceChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForceChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ForceChangeRate left, ForceChangeRate right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ForceChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForceChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ForceChangeRate left, ForceChangeRate right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ForceChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForceChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ForceChangeRate otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ForceChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForceChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ForceChangeRate other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ForceChangeRate"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ForceChangeRate otherQuantity)) throw new ArgumentException("Expected type ForceChangeRate.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ForceChangeRate"/> with another <see cref="ForceChangeRate"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ForceChangeRate other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ForceChangeRate within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ForceChangeRate.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ForceChangeRateUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ForceChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ForceChangeRate with the specified unit.</returns> + public ForceChangeRate ToUnit(ForceChangeRateUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ForceChangeRate"/> to another <see cref="ForceChangeRate"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ForceChangeRate with the specified unit.</returns> + public ForceChangeRate ToUnit(ForceChangeRateUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ForceChangeRate), Unit, typeof(ForceChangeRate), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ForceChangeRate)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ForceChangeRate"/> to another <see cref="ForceChangeRate"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ForceChangeRate"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ForceChangeRateUnit unit, [NotNullWhen(true)] out ForceChangeRate? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ForceChangeRate? convertedOrNull = (Unit, unit) switch + { + // ForceChangeRateUnit -> BaseUnit + (ForceChangeRateUnit.CentinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-2d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.DecanewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value / 60) * 1e1d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.DecanewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e1d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.DecinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-1d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.KilonewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value / 60) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.KilonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.KilopoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value * 4.4482216152605095551842641431421 / 60) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.KilopoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value * 4.4482216152605095551842641431421) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-6d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.MillinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-3d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.NanonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-9d, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.NewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate(_value / 60, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.PoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate(_value * 4.4482216152605095551842641431421 / 60, ForceChangeRateUnit.NewtonPerSecond), + (ForceChangeRateUnit.PoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate(_value * 4.4482216152605095551842641431421, ForceChangeRateUnit.NewtonPerSecond), + + // BaseUnit -> ForceChangeRateUnit + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.CentinewtonPerSecond) => new ForceChangeRate((_value) / 1e-2d, ForceChangeRateUnit.CentinewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerMinute) => new ForceChangeRate((_value * 60) / 1e1d, ForceChangeRateUnit.DecanewtonPerMinute), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerSecond) => new ForceChangeRate((_value) / 1e1d, ForceChangeRateUnit.DecanewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecinewtonPerSecond) => new ForceChangeRate((_value) / 1e-1d, ForceChangeRateUnit.DecinewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerMinute) => new ForceChangeRate((_value * 60) / 1e3d, ForceChangeRateUnit.KilonewtonPerMinute), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerSecond) => new ForceChangeRate((_value) / 1e3d, ForceChangeRateUnit.KilonewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerMinute) => new ForceChangeRate((_value / 4.4482216152605095551842641431421 * 60) / 1e3d, ForceChangeRateUnit.KilopoundForcePerMinute), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerSecond) => new ForceChangeRate((_value / 4.4482216152605095551842641431421) / 1e3d, ForceChangeRateUnit.KilopoundForcePerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MicronewtonPerSecond) => new ForceChangeRate((_value) / 1e-6d, ForceChangeRateUnit.MicronewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MillinewtonPerSecond) => new ForceChangeRate((_value) / 1e-3d, ForceChangeRateUnit.MillinewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NanonewtonPerSecond) => new ForceChangeRate((_value) / 1e-9d, ForceChangeRateUnit.NanonewtonPerSecond), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerMinute) => new ForceChangeRate(_value * 60, ForceChangeRateUnit.NewtonPerMinute), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerMinute) => new ForceChangeRate(_value / 4.4482216152605095551842641431421 * 60, ForceChangeRateUnit.PoundForcePerMinute), + (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerSecond) => new ForceChangeRate(_value / 4.4482216152605095551842641431421, ForceChangeRateUnit.PoundForcePerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ForceChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ForceChangeRateUnit> IQuantity<ForceChangeRateUnit>.ToUnit(ForceChangeRateUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ForceChangeRateUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ForceChangeRate)) + return this; + else if (conversionType == typeof(ForceChangeRateUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ForceChangeRate.Info; + else if (conversionType == typeof(BaseDimensions)) + return ForceChangeRate.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRateUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRateUnit.g.cs new file mode 100644 index 0000000000..9b76b2f23a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ForceChangeRate/ForceChangeRateUnit.g.cs @@ -0,0 +1,46 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ForceChangeRateUnit + { + CentinewtonPerSecond = 1, + DecanewtonPerMinute = 2, + DecanewtonPerSecond = 3, + DecinewtonPerSecond = 4, + KilonewtonPerMinute = 5, + KilonewtonPerSecond = 6, + KilopoundForcePerMinute = 7, + KilopoundForcePerSecond = 8, + MicronewtonPerSecond = 9, + MillinewtonPerSecond = 10, + NanonewtonPerSecond = 11, + NewtonPerMinute = 12, + NewtonPerSecond = 13, + PoundForcePerMinute = 14, + PoundForcePerSecond = 15, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLength.csproj b/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLength.csproj new file mode 100644 index 0000000000..532ec7d28a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLength.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ForcePerLength</Title> + <Description>Adds ForcePerLength units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>forceperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{6b975d30-c5dd-f1fd-9d0c-4d56ecdf9b25}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ForcePerLength</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLength.g.cs b/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLength.g.cs new file mode 100644 index 0000000000..353ebc3e2d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLength.g.cs @@ -0,0 +1,1621 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The magnitude of force per unit length. + /// </summary> + [DataContract] + public readonly partial struct ForcePerLength : IArithmeticQuantity<ForcePerLength, ForcePerLengthUnit, double>, IEquatable<ForcePerLength>, IComparable, IComparable<ForcePerLength>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ForcePerLengthUnit? _unit; + + static ForcePerLength() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + BaseUnit = ForcePerLengthUnit.NewtonPerMeter; + Units = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast<ForcePerLengthUnit>().ToArray(); + Zero = new ForcePerLength(0, BaseUnit); + Info = new QuantityInfo<ForcePerLengthUnit>("ForcePerLength", + new UnitInfo<ForcePerLengthUnit>[] + { + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.CentinewtonPerCentimeter, "CentinewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.CentinewtonPerMeter, "CentinewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.CentinewtonPerMillimeter, "CentinewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.DecanewtonPerCentimeter, "DecanewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.DecanewtonPerMeter, "DecanewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.DecanewtonPerMillimeter, "DecanewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.DecinewtonPerCentimeter, "DecinewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.DecinewtonPerMeter, "DecinewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.DecinewtonPerMillimeter, "DecinewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilogramForcePerCentimeter, "KilogramsForcePerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilogramForcePerMeter, "KilogramsForcePerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilogramForcePerMillimeter, "KilogramsForcePerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilonewtonPerCentimeter, "KilonewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilonewtonPerMeter, "KilonewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilonewtonPerMillimeter, "KilonewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilopoundForcePerFoot, "KilopoundsForcePerFoot", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.KilopoundForcePerInch, "KilopoundsForcePerInch", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MeganewtonPerCentimeter, "MeganewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MeganewtonPerMeter, "MeganewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MeganewtonPerMillimeter, "MeganewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MicronewtonPerCentimeter, "MicronewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MicronewtonPerMeter, "MicronewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MicronewtonPerMillimeter, "MicronewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MillinewtonPerCentimeter, "MillinewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MillinewtonPerMeter, "MillinewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.MillinewtonPerMillimeter, "MillinewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.NanonewtonPerCentimeter, "NanonewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.NanonewtonPerMeter, "NanonewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.NanonewtonPerMillimeter, "NanonewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.NewtonPerCentimeter, "NewtonsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.NewtonPerMeter, "NewtonsPerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.NewtonPerMillimeter, "NewtonsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.PoundForcePerFoot, "PoundsForcePerFoot", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.PoundForcePerInch, "PoundsForcePerInch", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.PoundForcePerYard, "PoundsForcePerYard", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.TonneForcePerCentimeter, "TonnesForcePerCentimeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.TonneForcePerMeter, "TonnesForcePerMeter", BaseUnits.Undefined), + new UnitInfo<ForcePerLengthUnit>(ForcePerLengthUnit.TonneForcePerMillimeter, "TonnesForcePerMillimeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ForcePerLength(double value, ForcePerLengthUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ForcePerLength" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ForcePerLengthUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. + /// </summary> + public static ForcePerLengthUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ForcePerLength quantity. + /// </summary> + public static ForcePerLengthUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. + /// </summary> + public static ForcePerLength Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ForcePerLength AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ForcePerLengthUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.CentinewtonPerCentimeter"/> + /// </summary> + public double CentinewtonsPerCentimeter => As(ForcePerLengthUnit.CentinewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.CentinewtonPerMeter"/> + /// </summary> + public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.CentinewtonPerMillimeter"/> + /// </summary> + public double CentinewtonsPerMillimeter => As(ForcePerLengthUnit.CentinewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.DecanewtonPerCentimeter"/> + /// </summary> + public double DecanewtonsPerCentimeter => As(ForcePerLengthUnit.DecanewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.DecanewtonPerMeter"/> + /// </summary> + public double DecanewtonsPerMeter => As(ForcePerLengthUnit.DecanewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.DecanewtonPerMillimeter"/> + /// </summary> + public double DecanewtonsPerMillimeter => As(ForcePerLengthUnit.DecanewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.DecinewtonPerCentimeter"/> + /// </summary> + public double DecinewtonsPerCentimeter => As(ForcePerLengthUnit.DecinewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.DecinewtonPerMeter"/> + /// </summary> + public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.DecinewtonPerMillimeter"/> + /// </summary> + public double DecinewtonsPerMillimeter => As(ForcePerLengthUnit.DecinewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilogramForcePerCentimeter"/> + /// </summary> + public double KilogramsForcePerCentimeter => As(ForcePerLengthUnit.KilogramForcePerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilogramForcePerMeter"/> + /// </summary> + public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilogramForcePerMillimeter"/> + /// </summary> + public double KilogramsForcePerMillimeter => As(ForcePerLengthUnit.KilogramForcePerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilonewtonPerCentimeter"/> + /// </summary> + public double KilonewtonsPerCentimeter => As(ForcePerLengthUnit.KilonewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilonewtonPerMeter"/> + /// </summary> + public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilonewtonPerMillimeter"/> + /// </summary> + public double KilonewtonsPerMillimeter => As(ForcePerLengthUnit.KilonewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilopoundForcePerFoot"/> + /// </summary> + public double KilopoundsForcePerFoot => As(ForcePerLengthUnit.KilopoundForcePerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.KilopoundForcePerInch"/> + /// </summary> + public double KilopoundsForcePerInch => As(ForcePerLengthUnit.KilopoundForcePerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MeganewtonPerCentimeter"/> + /// </summary> + public double MeganewtonsPerCentimeter => As(ForcePerLengthUnit.MeganewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MeganewtonPerMeter"/> + /// </summary> + public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MeganewtonPerMillimeter"/> + /// </summary> + public double MeganewtonsPerMillimeter => As(ForcePerLengthUnit.MeganewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MicronewtonPerCentimeter"/> + /// </summary> + public double MicronewtonsPerCentimeter => As(ForcePerLengthUnit.MicronewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MicronewtonPerMeter"/> + /// </summary> + public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MicronewtonPerMillimeter"/> + /// </summary> + public double MicronewtonsPerMillimeter => As(ForcePerLengthUnit.MicronewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MillinewtonPerCentimeter"/> + /// </summary> + public double MillinewtonsPerCentimeter => As(ForcePerLengthUnit.MillinewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MillinewtonPerMeter"/> + /// </summary> + public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.MillinewtonPerMillimeter"/> + /// </summary> + public double MillinewtonsPerMillimeter => As(ForcePerLengthUnit.MillinewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.NanonewtonPerCentimeter"/> + /// </summary> + public double NanonewtonsPerCentimeter => As(ForcePerLengthUnit.NanonewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.NanonewtonPerMeter"/> + /// </summary> + public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.NanonewtonPerMillimeter"/> + /// </summary> + public double NanonewtonsPerMillimeter => As(ForcePerLengthUnit.NanonewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.NewtonPerCentimeter"/> + /// </summary> + public double NewtonsPerCentimeter => As(ForcePerLengthUnit.NewtonPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.NewtonPerMeter"/> + /// </summary> + public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.NewtonPerMillimeter"/> + /// </summary> + public double NewtonsPerMillimeter => As(ForcePerLengthUnit.NewtonPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.PoundForcePerFoot"/> + /// </summary> + public double PoundsForcePerFoot => As(ForcePerLengthUnit.PoundForcePerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.PoundForcePerInch"/> + /// </summary> + public double PoundsForcePerInch => As(ForcePerLengthUnit.PoundForcePerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.PoundForcePerYard"/> + /// </summary> + public double PoundsForcePerYard => As(ForcePerLengthUnit.PoundForcePerYard); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.TonneForcePerCentimeter"/> + /// </summary> + public double TonnesForcePerCentimeter => As(ForcePerLengthUnit.TonneForcePerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.TonneForcePerMeter"/> + /// </summary> + public double TonnesForcePerMeter => As(ForcePerLengthUnit.TonneForcePerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ForcePerLengthUnit.TonneForcePerMillimeter"/> + /// </summary> + public double TonnesForcePerMillimeter => As(ForcePerLengthUnit.TonneForcePerMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ForcePerLengthUnit -> BaseUnit + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.CentinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.CentinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.CentinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.DecanewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.DecanewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.DecanewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.DecinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.DecinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.DecinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilogramForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilogramForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilogramForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilopoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.KilopoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MeganewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MeganewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MeganewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MicronewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MicronewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MillinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MillinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.MillinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NanonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NanonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NanonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.PoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.PoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.PoundForcePerYard, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.TonneForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.TonneForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.TonneForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ForcePerLengthUnit + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerFoot, quantity => quantity.ToUnit(ForcePerLengthUnit.KilopoundForcePerFoot)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerInch, quantity => quantity.ToUnit(ForcePerLengthUnit.KilopoundForcePerInch)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMillimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerFoot, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerFoot)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerInch, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerInch)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerYard, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerYard)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerCentimeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerMeter)); + unitConverter.SetConversionFunction<ForcePerLength>(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.CentinewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.CentinewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"cN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.CentinewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"cN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.DecanewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"daN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.DecanewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"daN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.DecanewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"daN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.DecinewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"dN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.DecinewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"dN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.DecinewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"dN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilogramForcePerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilogramForcePerCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"кгс/см"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilogramForcePerMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilogramForcePerMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кгс/м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilogramForcePerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilogramForcePerMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"кгс/мм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilonewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilonewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilonewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilopoundForcePerFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf/ft", "kip/ft", "k/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.KilopoundForcePerInch, new CultureInfo("en-US"), false, true, new string[]{"kipf/in", "kip/in", "k/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MeganewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"MN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MeganewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"MN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MeganewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"MN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MicronewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"µN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MicronewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"µN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MicronewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"µN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MillinewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MillinewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"mN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.MillinewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.NanonewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"nN/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.NanonewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"nN/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.NanonewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"nN/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.NewtonPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"N/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.NewtonPerMeter, new CultureInfo("en-US"), false, true, new string[]{"N/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.NewtonPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"N/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.PoundForcePerFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.PoundForcePerInch, new CultureInfo("en-US"), false, true, new string[]{"lbf/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.PoundForcePerYard, new CultureInfo("en-US"), false, true, new string[]{"lbf/yd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.TonneForcePerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"tf/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.TonneForcePerCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"тс/см"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.TonneForcePerMeter, new CultureInfo("en-US"), false, true, new string[]{"tf/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.TonneForcePerMeter, new CultureInfo("ru-RU"), false, true, new string[]{"тс/м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.TonneForcePerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"tf/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ForcePerLengthUnit.TonneForcePerMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"тс/мм"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ForcePerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ForcePerLengthUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.CentinewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromCentinewtonsPerCentimeter(QuantityValue centinewtonspercentimeter) + { + double value = (double) centinewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.CentinewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) + { + double value = (double) centinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.CentinewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromCentinewtonsPerMillimeter(QuantityValue centinewtonspermillimeter) + { + double value = (double) centinewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.DecanewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromDecanewtonsPerCentimeter(QuantityValue decanewtonspercentimeter) + { + double value = (double) decanewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.DecanewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromDecanewtonsPerMeter(QuantityValue decanewtonspermeter) + { + double value = (double) decanewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.DecanewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromDecanewtonsPerMillimeter(QuantityValue decanewtonspermillimeter) + { + double value = (double) decanewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.DecinewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromDecinewtonsPerCentimeter(QuantityValue decinewtonspercentimeter) + { + double value = (double) decinewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.DecinewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) + { + double value = (double) decinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.DecinewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromDecinewtonsPerMillimeter(QuantityValue decinewtonspermillimeter) + { + double value = (double) decinewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilogramForcePerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilogramsForcePerCentimeter(QuantityValue kilogramsforcepercentimeter) + { + double value = (double) kilogramsforcepercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilogramForcePerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) + { + double value = (double) kilogramsforcepermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilogramForcePerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilogramsForcePerMillimeter(QuantityValue kilogramsforcepermillimeter) + { + double value = (double) kilogramsforcepermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilonewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilonewtonsPerCentimeter(QuantityValue kilonewtonspercentimeter) + { + double value = (double) kilonewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilonewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) + { + double value = (double) kilonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilonewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilonewtonsPerMillimeter(QuantityValue kilonewtonspermillimeter) + { + double value = (double) kilonewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilopoundForcePerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilopoundsForcePerFoot(QuantityValue kilopoundsforceperfoot) + { + double value = (double) kilopoundsforceperfoot; + return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerFoot); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.KilopoundForcePerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromKilopoundsForcePerInch(QuantityValue kilopoundsforceperinch) + { + double value = (double) kilopoundsforceperinch; + return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerInch); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MeganewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMeganewtonsPerCentimeter(QuantityValue meganewtonspercentimeter) + { + double value = (double) meganewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MeganewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) + { + double value = (double) meganewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MeganewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMeganewtonsPerMillimeter(QuantityValue meganewtonspermillimeter) + { + double value = (double) meganewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MicronewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMicronewtonsPerCentimeter(QuantityValue micronewtonspercentimeter) + { + double value = (double) micronewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MicronewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) + { + double value = (double) micronewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MicronewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMicronewtonsPerMillimeter(QuantityValue micronewtonspermillimeter) + { + double value = (double) micronewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MillinewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMillinewtonsPerCentimeter(QuantityValue millinewtonspercentimeter) + { + double value = (double) millinewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MillinewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) + { + double value = (double) millinewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.MillinewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromMillinewtonsPerMillimeter(QuantityValue millinewtonspermillimeter) + { + double value = (double) millinewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.NanonewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromNanonewtonsPerCentimeter(QuantityValue nanonewtonspercentimeter) + { + double value = (double) nanonewtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.NanonewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) + { + double value = (double) nanonewtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.NanonewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromNanonewtonsPerMillimeter(QuantityValue nanonewtonspermillimeter) + { + double value = (double) nanonewtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.NewtonPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromNewtonsPerCentimeter(QuantityValue newtonspercentimeter) + { + double value = (double) newtonspercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.NewtonPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) + { + double value = (double) newtonspermeter; + return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.NewtonPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromNewtonsPerMillimeter(QuantityValue newtonspermillimeter) + { + double value = (double) newtonspermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.PoundForcePerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromPoundsForcePerFoot(QuantityValue poundsforceperfoot) + { + double value = (double) poundsforceperfoot; + return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerFoot); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.PoundForcePerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromPoundsForcePerInch(QuantityValue poundsforceperinch) + { + double value = (double) poundsforceperinch; + return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerInch); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.PoundForcePerYard"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromPoundsForcePerYard(QuantityValue poundsforceperyard) + { + double value = (double) poundsforceperyard; + return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerYard); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.TonneForcePerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromTonnesForcePerCentimeter(QuantityValue tonnesforcepercentimeter) + { + double value = (double) tonnesforcepercentimeter; + return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerCentimeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.TonneForcePerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromTonnesForcePerMeter(QuantityValue tonnesforcepermeter) + { + double value = (double) tonnesforcepermeter; + return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMeter); + } + + /// <summary> + /// Creates a <see cref="ForcePerLength"/> from <see cref="ForcePerLengthUnit.TonneForcePerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ForcePerLength FromTonnesForcePerMillimeter(QuantityValue tonnesforcepermillimeter) + { + double value = (double) tonnesforcepermillimeter; + return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ForcePerLengthUnit" /> to <see cref="ForcePerLength" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ForcePerLength unit value.</returns> + public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) + { + return new ForcePerLength((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ForcePerLength Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ForcePerLength Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ForcePerLength, ForcePerLengthUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ForcePerLength result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ForcePerLength result) + { + return QuantityParser.Default.TryParse<ForcePerLength, ForcePerLengthUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ForcePerLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ForcePerLengthUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ForcePerLengthUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ForcePerLengthUnit)"/> + public static bool TryParseUnit(string str, out ForcePerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ForcePerLengthUnit unit) + { + return UnitParser.Default.TryParse<ForcePerLengthUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ForcePerLength operator -(ForcePerLength right) + { + return new ForcePerLength(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ForcePerLength"/> from adding two <see cref="ForcePerLength"/>.</summary> + public static ForcePerLength operator +(ForcePerLength left, ForcePerLength right) + { + return new ForcePerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ForcePerLength"/> from subtracting two <see cref="ForcePerLength"/>.</summary> + public static ForcePerLength operator -(ForcePerLength left, ForcePerLength right) + { + return new ForcePerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ForcePerLength"/> from multiplying value and <see cref="ForcePerLength"/>.</summary> + public static ForcePerLength operator *(double left, ForcePerLength right) + { + return new ForcePerLength(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ForcePerLength"/> from multiplying value and <see cref="ForcePerLength"/>.</summary> + public static ForcePerLength operator *(ForcePerLength left, double right) + { + return new ForcePerLength(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ForcePerLength"/> from dividing <see cref="ForcePerLength"/> by value.</summary> + public static ForcePerLength operator /(ForcePerLength left, double right) + { + return new ForcePerLength(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ForcePerLength"/> by <see cref="ForcePerLength"/>.</summary> + public static double operator /(ForcePerLength left, ForcePerLength right) + { + return left.NewtonsPerMeter / right.NewtonsPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ForcePerLength left, ForcePerLength right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ForcePerLength left, ForcePerLength right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ForcePerLength left, ForcePerLength right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ForcePerLength left, ForcePerLength right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ForcePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForcePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ForcePerLength left, ForcePerLength right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ForcePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForcePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ForcePerLength left, ForcePerLength right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ForcePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForcePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ForcePerLength otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ForcePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ForcePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ForcePerLength other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ForcePerLength"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ForcePerLength otherQuantity)) throw new ArgumentException("Expected type ForcePerLength.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ForcePerLength"/> with another <see cref="ForcePerLength"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ForcePerLength other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ForcePerLength within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ForcePerLength.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ForcePerLengthUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ForcePerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ForcePerLength to another ForcePerLength with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ForcePerLength with the specified unit.</returns> + public ForcePerLength ToUnit(ForcePerLengthUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ForcePerLength"/> to another <see cref="ForcePerLength"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ForcePerLength with the specified unit.</returns> + public ForcePerLength ToUnit(ForcePerLengthUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ForcePerLength), Unit, typeof(ForcePerLength), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ForcePerLength)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ForcePerLength"/> to another <see cref="ForcePerLength"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ForcePerLength"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ForcePerLengthUnit unit, [NotNullWhen(true)] out ForcePerLength? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ForcePerLength? convertedOrNull = (Unit, unit) switch + { + // ForcePerLengthUnit -> BaseUnit + (ForcePerLengthUnit.CentinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.CentinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.CentinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.DecanewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e1d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.DecanewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e1d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.DecanewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e1d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.DecinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.DecinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.DecinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilogramForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 980.665002864, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilogramForcePerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665002864, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilogramForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665002864e3, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e3d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e3d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e3d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilopoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 14593.90292, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.KilopoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 1.75126835e5, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MeganewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e6d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MeganewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e6d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MeganewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e6d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MicronewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MicronewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MillinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MillinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.MillinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.NanonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.NanonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.NanonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.NewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 1e2, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 1e3, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.PoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 14.59390292, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.PoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 1.75126835e2, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.PoundForcePerYard, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 4.864634307, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.TonneForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665002864e5, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.TonneForcePerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665002864e3, ForcePerLengthUnit.NewtonPerMeter), + (ForcePerLengthUnit.TonneForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665002864e6, ForcePerLengthUnit.NewtonPerMeter), + + // BaseUnit -> ForcePerLengthUnit + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-2d, ForcePerLengthUnit.CentinewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMeter) => new ForcePerLength((_value) / 1e-2d, ForcePerLengthUnit.CentinewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-2d, ForcePerLengthUnit.CentinewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e1d, ForcePerLengthUnit.DecanewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMeter) => new ForcePerLength((_value) / 1e1d, ForcePerLengthUnit.DecanewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e1d, ForcePerLengthUnit.DecanewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-1d, ForcePerLengthUnit.DecinewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMeter) => new ForcePerLength((_value) / 1e-1d, ForcePerLengthUnit.DecinewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-1d, ForcePerLengthUnit.DecinewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerCentimeter) => new ForcePerLength(_value / 980.665002864, ForcePerLengthUnit.KilogramForcePerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMeter) => new ForcePerLength(_value / 9.80665002864, ForcePerLengthUnit.KilogramForcePerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMillimeter) => new ForcePerLength(_value / 9.80665002864e3, ForcePerLengthUnit.KilogramForcePerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e3d, ForcePerLengthUnit.KilonewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMeter) => new ForcePerLength((_value) / 1e3d, ForcePerLengthUnit.KilonewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e3d, ForcePerLengthUnit.KilonewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerFoot) => new ForcePerLength(_value / 14593.90292, ForcePerLengthUnit.KilopoundForcePerFoot), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerInch) => new ForcePerLength(_value / 1.75126835e5, ForcePerLengthUnit.KilopoundForcePerInch), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e6d, ForcePerLengthUnit.MeganewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMeter) => new ForcePerLength((_value) / 1e6d, ForcePerLengthUnit.MeganewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e6d, ForcePerLengthUnit.MeganewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-6d, ForcePerLengthUnit.MicronewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMeter) => new ForcePerLength((_value) / 1e-6d, ForcePerLengthUnit.MicronewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-6d, ForcePerLengthUnit.MicronewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-3d, ForcePerLengthUnit.MillinewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMeter) => new ForcePerLength((_value) / 1e-3d, ForcePerLengthUnit.MillinewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-3d, ForcePerLengthUnit.MillinewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-9d, ForcePerLengthUnit.NanonewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMeter) => new ForcePerLength((_value) / 1e-9d, ForcePerLengthUnit.NanonewtonPerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-9d, ForcePerLengthUnit.NanonewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerCentimeter) => new ForcePerLength(_value / 1e2, ForcePerLengthUnit.NewtonPerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMillimeter) => new ForcePerLength(_value / 1e3, ForcePerLengthUnit.NewtonPerMillimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerFoot) => new ForcePerLength(_value / 14.59390292, ForcePerLengthUnit.PoundForcePerFoot), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerInch) => new ForcePerLength(_value / 1.75126835e2, ForcePerLengthUnit.PoundForcePerInch), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerYard) => new ForcePerLength(_value / 4.864634307, ForcePerLengthUnit.PoundForcePerYard), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerCentimeter) => new ForcePerLength(_value / 9.80665002864e5, ForcePerLengthUnit.TonneForcePerCentimeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMeter) => new ForcePerLength(_value / 9.80665002864e3, ForcePerLengthUnit.TonneForcePerMeter), + (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMillimeter) => new ForcePerLength(_value / 9.80665002864e6, ForcePerLengthUnit.TonneForcePerMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ForcePerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ForcePerLengthUnit> IQuantity<ForcePerLengthUnit>.ToUnit(ForcePerLengthUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ForcePerLengthUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ForcePerLength)) + return this; + else if (conversionType == typeof(ForcePerLengthUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ForcePerLength.Info; + else if (conversionType == typeof(BaseDimensions)) + return ForcePerLength.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLengthUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLengthUnit.g.cs new file mode 100644 index 0000000000..7f6a376ca3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ForcePerLength/ForcePerLengthUnit.g.cs @@ -0,0 +1,69 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ForcePerLengthUnit + { + CentinewtonPerCentimeter = 1, + CentinewtonPerMeter = 2, + CentinewtonPerMillimeter = 3, + DecanewtonPerCentimeter = 4, + DecanewtonPerMeter = 5, + DecanewtonPerMillimeter = 6, + DecinewtonPerCentimeter = 7, + DecinewtonPerMeter = 8, + DecinewtonPerMillimeter = 9, + KilogramForcePerCentimeter = 10, + KilogramForcePerMeter = 11, + KilogramForcePerMillimeter = 12, + KilonewtonPerCentimeter = 13, + KilonewtonPerMeter = 14, + KilonewtonPerMillimeter = 15, + KilopoundForcePerFoot = 16, + KilopoundForcePerInch = 17, + MeganewtonPerCentimeter = 18, + MeganewtonPerMeter = 19, + MeganewtonPerMillimeter = 20, + MicronewtonPerCentimeter = 21, + MicronewtonPerMeter = 22, + MicronewtonPerMillimeter = 23, + MillinewtonPerCentimeter = 24, + MillinewtonPerMeter = 25, + MillinewtonPerMillimeter = 26, + NanonewtonPerCentimeter = 27, + NanonewtonPerMeter = 28, + NanonewtonPerMillimeter = 29, + NewtonPerCentimeter = 30, + NewtonPerMeter = 31, + NewtonPerMillimeter = 32, + PoundForcePerFoot = 33, + PoundForcePerInch = 34, + PoundForcePerYard = 35, + TonneForcePerCentimeter = 36, + TonneForcePerMeter = 37, + TonneForcePerMillimeter = 38, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Frequency/Frequency.csproj b/UnitsNet.Modular/GeneratedCode/Frequency/Frequency.csproj new file mode 100644 index 0000000000..129e57c6e1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Frequency/Frequency.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Frequency</Title> + <Description>Adds Frequency units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>frequency unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8d66b616-3198-b8a1-d2d0-03496db6a62b}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Frequency</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Frequency/Frequency.g.cs b/UnitsNet.Modular/GeneratedCode/Frequency/Frequency.g.cs new file mode 100644 index 0000000000..d27f6b420c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Frequency/Frequency.g.cs @@ -0,0 +1,1055 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The number of occurrences of a repeating event per unit time. + /// </summary> + [DataContract] + public readonly partial struct Frequency : IArithmeticQuantity<Frequency, FrequencyUnit, double>, IEquatable<Frequency>, IComparable, IComparable<Frequency>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly FrequencyUnit? _unit; + + static Frequency() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + BaseUnit = FrequencyUnit.Hertz; + Units = Enum.GetValues(typeof(FrequencyUnit)).Cast<FrequencyUnit>().ToArray(); + Zero = new Frequency(0, BaseUnit); + Info = new QuantityInfo<FrequencyUnit>("Frequency", + new UnitInfo<FrequencyUnit>[] + { + new UnitInfo<FrequencyUnit>(FrequencyUnit.BeatPerMinute, "BeatsPerMinute", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.BUnit, "BUnits", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.CyclePerHour, "CyclesPerHour", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.CyclePerMinute, "CyclesPerMinute", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.Gigahertz, "Gigahertz", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.Hertz, "Hertz", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.Kilohertz, "Kilohertz", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.Megahertz, "Megahertz", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.PerSecond, "PerSecond", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.RadianPerSecond, "RadiansPerSecond", BaseUnits.Undefined), + new UnitInfo<FrequencyUnit>(FrequencyUnit.Terahertz, "Terahertz", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Frequency(double value, FrequencyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Frequency" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<FrequencyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Frequency, which is Hertz. All conversions go via this value. + /// </summary> + public static FrequencyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Frequency quantity. + /// </summary> + public static FrequencyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. + /// </summary> + public static Frequency Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Frequency AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<FrequencyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Frequency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.BeatPerMinute"/> + /// </summary> + public double BeatsPerMinute => As(FrequencyUnit.BeatPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.BUnit"/> + /// </summary> + public double BUnits => As(FrequencyUnit.BUnit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.CyclePerHour"/> + /// </summary> + public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.CyclePerMinute"/> + /// </summary> + public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.Gigahertz"/> + /// </summary> + public double Gigahertz => As(FrequencyUnit.Gigahertz); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.Hertz"/> + /// </summary> + public double Hertz => As(FrequencyUnit.Hertz); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.Kilohertz"/> + /// </summary> + public double Kilohertz => As(FrequencyUnit.Kilohertz); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.Megahertz"/> + /// </summary> + public double Megahertz => As(FrequencyUnit.Megahertz); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.PerSecond"/> + /// </summary> + public double PerSecond => As(FrequencyUnit.PerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.RadianPerSecond"/> + /// </summary> + public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FrequencyUnit.Terahertz"/> + /// </summary> + public double Terahertz => As(FrequencyUnit.Terahertz); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: FrequencyUnit -> BaseUnit + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.BeatPerMinute, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.BUnit, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.CyclePerHour, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.CyclePerMinute, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Gigahertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Kilohertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Megahertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.PerSecond, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.RadianPerSecond, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Terahertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.Hertz, quantity => quantity); + + // Register in unit converter: BaseUnit -> FrequencyUnit + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.BeatPerMinute, quantity => quantity.ToUnit(FrequencyUnit.BeatPerMinute)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.BUnit, quantity => quantity.ToUnit(FrequencyUnit.BUnit)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.CyclePerHour, quantity => quantity.ToUnit(FrequencyUnit.CyclePerHour)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.CyclePerMinute, quantity => quantity.ToUnit(FrequencyUnit.CyclePerMinute)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.Gigahertz, quantity => quantity.ToUnit(FrequencyUnit.Gigahertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.Kilohertz, quantity => quantity.ToUnit(FrequencyUnit.Kilohertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.Megahertz, quantity => quantity.ToUnit(FrequencyUnit.Megahertz)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.PerSecond, quantity => quantity.ToUnit(FrequencyUnit.PerSecond)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.RadianPerSecond, quantity => quantity.ToUnit(FrequencyUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<Frequency>(FrequencyUnit.Hertz, FrequencyUnit.Terahertz, quantity => quantity.ToUnit(FrequencyUnit.Terahertz)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.BeatPerMinute, new CultureInfo("en-US"), false, true, new string[]{"bpm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.BUnit, new CultureInfo("en-US"), false, true, new string[]{"B Units"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.CyclePerHour, new CultureInfo("en-US"), false, true, new string[]{"cph"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.CyclePerMinute, new CultureInfo("en-US"), false, true, new string[]{"cpm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Gigahertz, new CultureInfo("en-US"), false, true, new string[]{"GHz"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Gigahertz, new CultureInfo("ru-RU"), false, true, new string[]{"ГГц"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Hertz, new CultureInfo("en-US"), false, true, new string[]{"Hz"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Hertz, new CultureInfo("ru-RU"), false, true, new string[]{"Гц"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Kilohertz, new CultureInfo("en-US"), false, true, new string[]{"kHz"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Kilohertz, new CultureInfo("ru-RU"), false, true, new string[]{"кГц"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Megahertz, new CultureInfo("en-US"), false, true, new string[]{"MHz"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Megahertz, new CultureInfo("ru-RU"), false, true, new string[]{"МГц"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.PerSecond, new CultureInfo("en-US"), false, true, new string[]{"s⁻¹"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.PerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"с⁻¹"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.RadianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"rad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.RadianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"рад/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Terahertz, new CultureInfo("en-US"), false, true, new string[]{"THz"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FrequencyUnit.Terahertz, new CultureInfo("ru-RU"), false, true, new string[]{"ТГц"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(FrequencyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(FrequencyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.BeatPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromBeatsPerMinute(QuantityValue beatsperminute) + { + double value = (double) beatsperminute; + return new Frequency(value, FrequencyUnit.BeatPerMinute); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.BUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromBUnits(QuantityValue bunits) + { + double value = (double) bunits; + return new Frequency(value, FrequencyUnit.BUnit); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.CyclePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) + { + double value = (double) cyclesperhour; + return new Frequency(value, FrequencyUnit.CyclePerHour); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.CyclePerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) + { + double value = (double) cyclesperminute; + return new Frequency(value, FrequencyUnit.CyclePerMinute); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.Gigahertz"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromGigahertz(QuantityValue gigahertz) + { + double value = (double) gigahertz; + return new Frequency(value, FrequencyUnit.Gigahertz); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.Hertz"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromHertz(QuantityValue hertz) + { + double value = (double) hertz; + return new Frequency(value, FrequencyUnit.Hertz); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.Kilohertz"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromKilohertz(QuantityValue kilohertz) + { + double value = (double) kilohertz; + return new Frequency(value, FrequencyUnit.Kilohertz); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.Megahertz"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromMegahertz(QuantityValue megahertz) + { + double value = (double) megahertz; + return new Frequency(value, FrequencyUnit.Megahertz); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.PerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromPerSecond(QuantityValue persecond) + { + double value = (double) persecond; + return new Frequency(value, FrequencyUnit.PerSecond); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.RadianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) + { + double value = (double) radianspersecond; + return new Frequency(value, FrequencyUnit.RadianPerSecond); + } + + /// <summary> + /// Creates a <see cref="Frequency"/> from <see cref="FrequencyUnit.Terahertz"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Frequency FromTerahertz(QuantityValue terahertz) + { + double value = (double) terahertz; + return new Frequency(value, FrequencyUnit.Terahertz); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="FrequencyUnit" /> to <see cref="Frequency" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Frequency unit value.</returns> + public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) + { + return new Frequency((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Frequency Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Frequency Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Frequency, FrequencyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Frequency result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Frequency result) + { + return QuantityParser.Default.TryParse<Frequency, FrequencyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static FrequencyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static FrequencyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<FrequencyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.FrequencyUnit)"/> + public static bool TryParseUnit(string str, out FrequencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out FrequencyUnit unit) + { + return UnitParser.Default.TryParse<FrequencyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Frequency operator -(Frequency right) + { + return new Frequency(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Frequency"/> from adding two <see cref="Frequency"/>.</summary> + public static Frequency operator +(Frequency left, Frequency right) + { + return new Frequency(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Frequency"/> from subtracting two <see cref="Frequency"/>.</summary> + public static Frequency operator -(Frequency left, Frequency right) + { + return new Frequency(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Frequency"/> from multiplying value and <see cref="Frequency"/>.</summary> + public static Frequency operator *(double left, Frequency right) + { + return new Frequency(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Frequency"/> from multiplying value and <see cref="Frequency"/>.</summary> + public static Frequency operator *(Frequency left, double right) + { + return new Frequency(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Frequency"/> from dividing <see cref="Frequency"/> by value.</summary> + public static Frequency operator /(Frequency left, double right) + { + return new Frequency(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Frequency"/> by <see cref="Frequency"/>.</summary> + public static double operator /(Frequency left, Frequency right) + { + return left.Hertz / right.Hertz; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Frequency left, Frequency right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Frequency left, Frequency right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Frequency left, Frequency right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Frequency left, Frequency right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Frequency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Frequency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Frequency left, Frequency right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Frequency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Frequency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Frequency left, Frequency right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Frequency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Frequency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Frequency otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Frequency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Frequency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Frequency other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Frequency"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Frequency otherQuantity)) throw new ArgumentException("Expected type Frequency.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Frequency"/> with another <see cref="Frequency"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Frequency other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Frequency within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Frequency.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(FrequencyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is FrequencyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Frequency to another Frequency with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Frequency with the specified unit.</returns> + public Frequency ToUnit(FrequencyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Frequency"/> to another <see cref="Frequency"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Frequency with the specified unit.</returns> + public Frequency ToUnit(FrequencyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Frequency), Unit, typeof(Frequency), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Frequency)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Frequency"/> to another <see cref="Frequency"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Frequency"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(FrequencyUnit unit, [NotNullWhen(true)] out Frequency? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Frequency? convertedOrNull = (Unit, unit) switch + { + // FrequencyUnit -> BaseUnit + (FrequencyUnit.BeatPerMinute, FrequencyUnit.Hertz) => new Frequency(_value / 60, FrequencyUnit.Hertz), + (FrequencyUnit.BUnit, FrequencyUnit.Hertz) => new Frequency(Math.Sqrt(_value * 1e3), FrequencyUnit.Hertz), + (FrequencyUnit.CyclePerHour, FrequencyUnit.Hertz) => new Frequency(_value / 3600, FrequencyUnit.Hertz), + (FrequencyUnit.CyclePerMinute, FrequencyUnit.Hertz) => new Frequency(_value / 60, FrequencyUnit.Hertz), + (FrequencyUnit.Gigahertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e9d, FrequencyUnit.Hertz), + (FrequencyUnit.Kilohertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e3d, FrequencyUnit.Hertz), + (FrequencyUnit.Megahertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e6d, FrequencyUnit.Hertz), + (FrequencyUnit.PerSecond, FrequencyUnit.Hertz) => new Frequency(_value, FrequencyUnit.Hertz), + (FrequencyUnit.RadianPerSecond, FrequencyUnit.Hertz) => new Frequency(_value / 6.2831853072, FrequencyUnit.Hertz), + (FrequencyUnit.Terahertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e12d, FrequencyUnit.Hertz), + + // BaseUnit -> FrequencyUnit + (FrequencyUnit.Hertz, FrequencyUnit.BeatPerMinute) => new Frequency(_value * 60, FrequencyUnit.BeatPerMinute), + (FrequencyUnit.Hertz, FrequencyUnit.BUnit) => new Frequency(_value * _value * 1e-3, FrequencyUnit.BUnit), + (FrequencyUnit.Hertz, FrequencyUnit.CyclePerHour) => new Frequency(_value * 3600, FrequencyUnit.CyclePerHour), + (FrequencyUnit.Hertz, FrequencyUnit.CyclePerMinute) => new Frequency(_value * 60, FrequencyUnit.CyclePerMinute), + (FrequencyUnit.Hertz, FrequencyUnit.Gigahertz) => new Frequency((_value) / 1e9d, FrequencyUnit.Gigahertz), + (FrequencyUnit.Hertz, FrequencyUnit.Kilohertz) => new Frequency((_value) / 1e3d, FrequencyUnit.Kilohertz), + (FrequencyUnit.Hertz, FrequencyUnit.Megahertz) => new Frequency((_value) / 1e6d, FrequencyUnit.Megahertz), + (FrequencyUnit.Hertz, FrequencyUnit.PerSecond) => new Frequency(_value, FrequencyUnit.PerSecond), + (FrequencyUnit.Hertz, FrequencyUnit.RadianPerSecond) => new Frequency(_value * 6.2831853072, FrequencyUnit.RadianPerSecond), + (FrequencyUnit.Hertz, FrequencyUnit.Terahertz) => new Frequency((_value) / 1e12d, FrequencyUnit.Terahertz), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is FrequencyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<FrequencyUnit> IQuantity<FrequencyUnit>.ToUnit(FrequencyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<FrequencyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Frequency)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Frequency)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Frequency)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Frequency)) + return this; + else if (conversionType == typeof(FrequencyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Frequency.Info; + else if (conversionType == typeof(BaseDimensions)) + return Frequency.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Frequency)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Frequency/FrequencyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Frequency/FrequencyUnit.g.cs new file mode 100644 index 0000000000..c78283ce9c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Frequency/FrequencyUnit.g.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum FrequencyUnit + { + BeatPerMinute = 1, + BUnit = 2, + CyclePerHour = 3, + CyclePerMinute = 4, + Gigahertz = 5, + Hertz = 6, + Kilohertz = 7, + Megahertz = 8, + PerSecond = 9, + RadianPerSecond = 10, + Terahertz = 11, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiency.csproj b/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiency.csproj new file mode 100644 index 0000000000..0747bb2ea5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiency.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET FuelEfficiency</Title> + <Description>Adds FuelEfficiency units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>fuelefficiency unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{6e68ff9b-3947-d706-3ad7-f9237a67c874}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.FuelEfficiency</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiency.g.cs b/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiency.g.cs new file mode 100644 index 0000000000..95e87a9f56 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiency.g.cs @@ -0,0 +1,904 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as "fuel consumption" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon). + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Fuel_efficiency + /// </remarks> + [DataContract] + public readonly partial struct FuelEfficiency : IArithmeticQuantity<FuelEfficiency, FuelEfficiencyUnit, double>, IEquatable<FuelEfficiency>, IComparable, IComparable<FuelEfficiency>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly FuelEfficiencyUnit? _unit; + + static FuelEfficiency() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = FuelEfficiencyUnit.LiterPer100Kilometers; + Units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast<FuelEfficiencyUnit>().ToArray(); + Zero = new FuelEfficiency(0, BaseUnit); + Info = new QuantityInfo<FuelEfficiencyUnit>("FuelEfficiency", + new UnitInfo<FuelEfficiencyUnit>[] + { + new UnitInfo<FuelEfficiencyUnit>(FuelEfficiencyUnit.KilometerPerLiter, "KilometersPerLiters", BaseUnits.Undefined), + new UnitInfo<FuelEfficiencyUnit>(FuelEfficiencyUnit.LiterPer100Kilometers, "LitersPer100Kilometers", BaseUnits.Undefined), + new UnitInfo<FuelEfficiencyUnit>(FuelEfficiencyUnit.MilePerUkGallon, "MilesPerUkGallon", BaseUnits.Undefined), + new UnitInfo<FuelEfficiencyUnit>(FuelEfficiencyUnit.MilePerUsGallon, "MilesPerUsGallon", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public FuelEfficiency(double value, FuelEfficiencyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="FuelEfficiency" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<FuelEfficiencyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of FuelEfficiency, which is LiterPer100Kilometers. All conversions go via this value. + /// </summary> + public static FuelEfficiencyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the FuelEfficiency quantity. + /// </summary> + public static FuelEfficiencyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit LiterPer100Kilometers. + /// </summary> + public static FuelEfficiency Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static FuelEfficiency AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<FuelEfficiencyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => FuelEfficiency.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.KilometerPerLiter"/> + /// </summary> + public double KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.LiterPer100Kilometers"/> + /// </summary> + public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.MilePerUkGallon"/> + /// </summary> + public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.MilePerUsGallon"/> + /// </summary> + public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: FuelEfficiencyUnit -> BaseUnit + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToUnit(FuelEfficiencyUnit.LiterPer100Kilometers)); + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToUnit(FuelEfficiencyUnit.LiterPer100Kilometers)); + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToUnit(FuelEfficiencyUnit.LiterPer100Kilometers)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity); + + // Register in unit converter: BaseUnit -> FuelEfficiencyUnit + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.KilometerPerLiter, quantity => quantity.ToUnit(FuelEfficiencyUnit.KilometerPerLiter)); + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUkGallon, quantity => quantity.ToUnit(FuelEfficiencyUnit.MilePerUkGallon)); + unitConverter.SetConversionFunction<FuelEfficiency>(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUsGallon, quantity => quantity.ToUnit(FuelEfficiencyUnit.MilePerUsGallon)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.KilometerPerLiter, new CultureInfo("en-US"), false, true, new string[]{"km/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.LiterPer100Kilometers, new CultureInfo("en-US"), false, true, new string[]{"L/100km"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.MilePerUkGallon, new CultureInfo("en-US"), false, true, new string[]{"mpg (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.MilePerUsGallon, new CultureInfo("en-US"), false, true, new string[]{"mpg (U.S.)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(FuelEfficiencyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(FuelEfficiencyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.KilometerPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static FuelEfficiency FromKilometersPerLiters(QuantityValue kilometersperliters) + { + double value = (double) kilometersperliters; + return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); + } + + /// <summary> + /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.LiterPer100Kilometers"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static FuelEfficiency FromLitersPer100Kilometers(QuantityValue litersper100kilometers) + { + double value = (double) litersper100kilometers; + return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); + } + + /// <summary> + /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.MilePerUkGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static FuelEfficiency FromMilesPerUkGallon(QuantityValue milesperukgallon) + { + double value = (double) milesperukgallon; + return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); + } + + /// <summary> + /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.MilePerUsGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static FuelEfficiency FromMilesPerUsGallon(QuantityValue milesperusgallon) + { + double value = (double) milesperusgallon; + return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="FuelEfficiencyUnit" /> to <see cref="FuelEfficiency" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>FuelEfficiency unit value.</returns> + public static FuelEfficiency From(QuantityValue value, FuelEfficiencyUnit fromUnit) + { + return new FuelEfficiency((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static FuelEfficiency Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static FuelEfficiency Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<FuelEfficiency, FuelEfficiencyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out FuelEfficiency result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out FuelEfficiency result) + { + return QuantityParser.Default.TryParse<FuelEfficiency, FuelEfficiencyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static FuelEfficiencyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static FuelEfficiencyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<FuelEfficiencyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.FuelEfficiencyUnit)"/> + public static bool TryParseUnit(string str, out FuelEfficiencyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out FuelEfficiencyUnit unit) + { + return UnitParser.Default.TryParse<FuelEfficiencyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static FuelEfficiency operator -(FuelEfficiency right) + { + return new FuelEfficiency(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="FuelEfficiency"/> from adding two <see cref="FuelEfficiency"/>.</summary> + public static FuelEfficiency operator +(FuelEfficiency left, FuelEfficiency right) + { + return new FuelEfficiency(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="FuelEfficiency"/> from subtracting two <see cref="FuelEfficiency"/>.</summary> + public static FuelEfficiency operator -(FuelEfficiency left, FuelEfficiency right) + { + return new FuelEfficiency(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="FuelEfficiency"/> from multiplying value and <see cref="FuelEfficiency"/>.</summary> + public static FuelEfficiency operator *(double left, FuelEfficiency right) + { + return new FuelEfficiency(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="FuelEfficiency"/> from multiplying value and <see cref="FuelEfficiency"/>.</summary> + public static FuelEfficiency operator *(FuelEfficiency left, double right) + { + return new FuelEfficiency(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="FuelEfficiency"/> from dividing <see cref="FuelEfficiency"/> by value.</summary> + public static FuelEfficiency operator /(FuelEfficiency left, double right) + { + return new FuelEfficiency(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="FuelEfficiency"/> by <see cref="FuelEfficiency"/>.</summary> + public static double operator /(FuelEfficiency left, FuelEfficiency right) + { + return left.LitersPer100Kilometers / right.LitersPer100Kilometers; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(FuelEfficiency left, FuelEfficiency right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(FuelEfficiency left, FuelEfficiency right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(FuelEfficiency left, FuelEfficiency right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(FuelEfficiency left, FuelEfficiency right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="FuelEfficiency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(FuelEfficiency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(FuelEfficiency left, FuelEfficiency right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="FuelEfficiency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(FuelEfficiency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(FuelEfficiency left, FuelEfficiency right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="FuelEfficiency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(FuelEfficiency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is FuelEfficiency otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="FuelEfficiency"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(FuelEfficiency, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(FuelEfficiency other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="FuelEfficiency"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is FuelEfficiency otherQuantity)) throw new ArgumentException("Expected type FuelEfficiency.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="FuelEfficiency"/> with another <see cref="FuelEfficiency"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(FuelEfficiency other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(FuelEfficiency other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current FuelEfficiency.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(FuelEfficiencyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is FuelEfficiencyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A FuelEfficiency with the specified unit.</returns> + public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="FuelEfficiency"/> to another <see cref="FuelEfficiency"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A FuelEfficiency with the specified unit.</returns> + public FuelEfficiency ToUnit(FuelEfficiencyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(FuelEfficiency), Unit, typeof(FuelEfficiency), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (FuelEfficiency)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="FuelEfficiency"/> to another <see cref="FuelEfficiency"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="FuelEfficiency"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(FuelEfficiencyUnit unit, [NotNullWhen(true)] out FuelEfficiency? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + FuelEfficiency? convertedOrNull = (Unit, unit) switch + { + // FuelEfficiencyUnit -> BaseUnit + (FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.LiterPer100Kilometers) => new FuelEfficiency(100 / _value, FuelEfficiencyUnit.LiterPer100Kilometers), + (FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiencyUnit.LiterPer100Kilometers) => new FuelEfficiency((100 * 4.54609188) / (1.609344 * _value), FuelEfficiencyUnit.LiterPer100Kilometers), + (FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiencyUnit.LiterPer100Kilometers) => new FuelEfficiency((100 * 3.785411784) / (1.609344 * _value), FuelEfficiencyUnit.LiterPer100Kilometers), + + // BaseUnit -> FuelEfficiencyUnit + (FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.KilometerPerLiter) => new FuelEfficiency(100 / _value, FuelEfficiencyUnit.KilometerPerLiter), + (FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUkGallon) => new FuelEfficiency((100 * 4.54609188) / (1.609344 * _value), FuelEfficiencyUnit.MilePerUkGallon), + (FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.MilePerUsGallon) => new FuelEfficiency((100 * 3.785411784) / (1.609344 * _value), FuelEfficiencyUnit.MilePerUsGallon), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is FuelEfficiencyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<FuelEfficiencyUnit> IQuantity<FuelEfficiencyUnit>.ToUnit(FuelEfficiencyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<FuelEfficiencyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(FuelEfficiency)) + return this; + else if (conversionType == typeof(FuelEfficiencyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return FuelEfficiency.Info; + else if (conversionType == typeof(BaseDimensions)) + return FuelEfficiency.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiencyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiencyUnit.g.cs new file mode 100644 index 0000000000..24491dee95 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/FuelEfficiency/FuelEfficiencyUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum FuelEfficiencyUnit + { + KilometerPerLiter = 1, + LiterPer100Kilometers = 2, + MilePerUkGallon = 3, + MilePerUsGallon = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFlux.csproj b/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFlux.csproj new file mode 100644 index 0000000000..3585883afa --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFlux.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET HeatFlux</Title> + <Description>Adds HeatFlux units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>heatflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{2b132458-96e5-72bf-673f-dda4a7fd514b}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.HeatFlux</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFlux.g.cs b/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFlux.g.cs new file mode 100644 index 0000000000..59138873ff --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFlux.g.cs @@ -0,0 +1,1195 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Heat flux is the flow of energy per unit of area per unit of time + /// </summary> + [DataContract] + public readonly partial struct HeatFlux : IArithmeticQuantity<HeatFlux, HeatFluxUnit, double>, IEquatable<HeatFlux>, IComparable, IComparable<HeatFlux>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly HeatFluxUnit? _unit; + + static HeatFlux() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + BaseUnit = HeatFluxUnit.WattPerSquareMeter; + Units = Enum.GetValues(typeof(HeatFluxUnit)).Cast<HeatFluxUnit>().ToArray(); + Zero = new HeatFlux(0, BaseUnit); + Info = new QuantityInfo<HeatFluxUnit>("HeatFlux", + new UnitInfo<HeatFluxUnit>[] + { + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.BtuPerHourSquareFoot, "BtusPerHourSquareFoot", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.BtuPerMinuteSquareFoot, "BtusPerMinuteSquareFoot", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.BtuPerSecondSquareFoot, "BtusPerSecondSquareFoot", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.BtuPerSecondSquareInch, "BtusPerSecondSquareInch", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.CaloriePerSecondSquareCentimeter, "CaloriesPerSecondSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.CentiwattPerSquareMeter, "CentiwattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.DeciwattPerSquareMeter, "DeciwattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.KilocaloriePerHourSquareMeter, "KilocaloriesPerHourSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, "KilocaloriesPerSecondSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.KilowattPerSquareMeter, "KilowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.MicrowattPerSquareMeter, "MicrowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.MilliwattPerSquareMeter, "MilliwattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.NanowattPerSquareMeter, "NanowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.PoundForcePerFootSecond, "PoundsForcePerFootSecond", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.PoundPerSecondCubed, "PoundsPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.WattPerSquareFoot, "WattsPerSquareFoot", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.WattPerSquareInch, "WattsPerSquareInch", BaseUnits.Undefined), + new UnitInfo<HeatFluxUnit>(HeatFluxUnit.WattPerSquareMeter, "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public HeatFlux(double value, HeatFluxUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="HeatFlux" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<HeatFluxUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. + /// </summary> + public static HeatFluxUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the HeatFlux quantity. + /// </summary> + public static HeatFluxUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// </summary> + public static HeatFlux Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static HeatFlux AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<HeatFluxUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => HeatFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.BtuPerHourSquareFoot"/> + /// </summary> + public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.BtuPerMinuteSquareFoot"/> + /// </summary> + public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.BtuPerSecondSquareFoot"/> + /// </summary> + public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.BtuPerSecondSquareInch"/> + /// </summary> + public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.CaloriePerSecondSquareCentimeter"/> + /// </summary> + public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.CentiwattPerSquareMeter"/> + /// </summary> + public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.DeciwattPerSquareMeter"/> + /// </summary> + public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.KilocaloriePerHourSquareMeter"/> + /// </summary> + public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.KilocaloriePerSecondSquareCentimeter"/> + /// </summary> + public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.KilowattPerSquareMeter"/> + /// </summary> + public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.MicrowattPerSquareMeter"/> + /// </summary> + public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.MilliwattPerSquareMeter"/> + /// </summary> + public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.NanowattPerSquareMeter"/> + /// </summary> + public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.PoundForcePerFootSecond"/> + /// </summary> + public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.PoundPerSecondCubed"/> + /// </summary> + public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.WattPerSquareFoot"/> + /// </summary> + public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.WattPerSquareInch"/> + /// </summary> + public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatFluxUnit.WattPerSquareMeter"/> + /// </summary> + public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: HeatFluxUnit -> BaseUnit + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.BtuPerHourSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.BtuPerMinuteSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.BtuPerSecondSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.BtuPerSecondSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.CaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.CentiwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.DeciwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.KilocaloriePerHourSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.KilowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.MicrowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.MilliwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.NanowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.PoundForcePerFootSecond, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.PoundPerSecondCubed, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> HeatFluxUnit + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerHourSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerHourSquareFoot)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerMinuteSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerMinuteSquareFoot)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerSecondSquareFoot)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareInch, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerSecondSquareInch)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CaloriePerSecondSquareCentimeter, quantity => quantity.ToUnit(HeatFluxUnit.CaloriePerSecondSquareCentimeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CentiwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.CentiwattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.DeciwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.DeciwattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerHourSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.KilocaloriePerHourSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, quantity => quantity.ToUnit(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.KilowattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MicrowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.MicrowattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MilliwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.MilliwattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.NanowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.NanowattPerSquareMeter)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundForcePerFootSecond, quantity => quantity.ToUnit(HeatFluxUnit.PoundForcePerFootSecond)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundPerSecondCubed, quantity => quantity.ToUnit(HeatFluxUnit.PoundPerSecondCubed)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareFoot)); + unitConverter.SetConversionFunction<HeatFlux>(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareInch, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareInch)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.BtuPerHourSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"BTU/h·ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.BtuPerMinuteSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"BTU/min·ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.BtuPerSecondSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"BTU/s·ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.BtuPerSecondSquareInch, new CultureInfo("en-US"), false, true, new string[]{"BTU/s·in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.CaloriePerSecondSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cal/s·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.CentiwattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"cW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.DeciwattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"dW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.KilocaloriePerHourSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kcal/h·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kcal/s·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.KilowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.MicrowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"µW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.MilliwattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"mW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.NanowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"nW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.PoundForcePerFootSecond, new CultureInfo("en-US"), false, true, new string[]{"lbf/(ft·s)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.PoundPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"lb/s³", "lbm/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.WattPerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"W/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.WattPerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"W/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatFluxUnit.WattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"W/m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(HeatFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(HeatFluxUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.BtuPerHourSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue btusperhoursquarefoot) + { + double value = (double) btusperhoursquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.BtuPerMinuteSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue btusperminutesquarefoot) + { + double value = (double) btusperminutesquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.BtuPerSecondSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue btuspersecondsquarefoot) + { + double value = (double) btuspersecondsquarefoot; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.BtuPerSecondSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue btuspersecondsquareinch) + { + double value = (double) btuspersecondsquareinch; + return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.CaloriePerSecondSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue caloriespersecondsquarecentimeter) + { + double value = (double) caloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.CentiwattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue centiwattspersquaremeter) + { + double value = (double) centiwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.DeciwattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue deciwattspersquaremeter) + { + double value = (double) deciwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.KilocaloriePerHourSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue kilocaloriesperhoursquaremeter) + { + double value = (double) kilocaloriesperhoursquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.KilocaloriePerSecondSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue kilocaloriespersecondsquarecentimeter) + { + double value = (double) kilocaloriespersecondsquarecentimeter; + return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.KilowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.MicrowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) + { + double value = (double) microwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.MilliwattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) + { + double value = (double) milliwattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.NanowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) + { + double value = (double) nanowattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.PoundForcePerFootSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromPoundsForcePerFootSecond(QuantityValue poundsforceperfootsecond) + { + double value = (double) poundsforceperfootsecond; + return new HeatFlux(value, HeatFluxUnit.PoundForcePerFootSecond); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.PoundPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromPoundsPerSecondCubed(QuantityValue poundspersecondcubed) + { + double value = (double) poundspersecondcubed; + return new HeatFlux(value, HeatFluxUnit.PoundPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.WattPerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromWattsPerSquareFoot(QuantityValue wattspersquarefoot) + { + double value = (double) wattspersquarefoot; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.WattPerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromWattsPerSquareInch(QuantityValue wattspersquareinch) + { + double value = (double) wattspersquareinch; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); + } + + /// <summary> + /// Creates a <see cref="HeatFlux"/> from <see cref="HeatFluxUnit.WattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatFlux FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) + { + double value = (double) wattspersquaremeter; + return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="HeatFluxUnit" /> to <see cref="HeatFlux" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>HeatFlux unit value.</returns> + public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) + { + return new HeatFlux((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static HeatFlux Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static HeatFlux Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<HeatFlux, HeatFluxUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out HeatFlux result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out HeatFlux result) + { + return QuantityParser.Default.TryParse<HeatFlux, HeatFluxUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static HeatFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static HeatFluxUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<HeatFluxUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.HeatFluxUnit)"/> + public static bool TryParseUnit(string str, out HeatFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatFluxUnit unit) + { + return UnitParser.Default.TryParse<HeatFluxUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static HeatFlux operator -(HeatFlux right) + { + return new HeatFlux(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="HeatFlux"/> from adding two <see cref="HeatFlux"/>.</summary> + public static HeatFlux operator +(HeatFlux left, HeatFlux right) + { + return new HeatFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="HeatFlux"/> from subtracting two <see cref="HeatFlux"/>.</summary> + public static HeatFlux operator -(HeatFlux left, HeatFlux right) + { + return new HeatFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="HeatFlux"/> from multiplying value and <see cref="HeatFlux"/>.</summary> + public static HeatFlux operator *(double left, HeatFlux right) + { + return new HeatFlux(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="HeatFlux"/> from multiplying value and <see cref="HeatFlux"/>.</summary> + public static HeatFlux operator *(HeatFlux left, double right) + { + return new HeatFlux(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="HeatFlux"/> from dividing <see cref="HeatFlux"/> by value.</summary> + public static HeatFlux operator /(HeatFlux left, double right) + { + return new HeatFlux(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="HeatFlux"/> by <see cref="HeatFlux"/>.</summary> + public static double operator /(HeatFlux left, HeatFlux right) + { + return left.WattsPerSquareMeter / right.WattsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(HeatFlux left, HeatFlux right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(HeatFlux left, HeatFlux right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(HeatFlux left, HeatFlux right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(HeatFlux left, HeatFlux right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="HeatFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(HeatFlux left, HeatFlux right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="HeatFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(HeatFlux left, HeatFlux right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="HeatFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is HeatFlux otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="HeatFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(HeatFlux other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="HeatFlux"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is HeatFlux otherQuantity)) throw new ArgumentException("Expected type HeatFlux.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="HeatFlux"/> with another <see cref="HeatFlux"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(HeatFlux other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another HeatFlux within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current HeatFlux.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(HeatFluxUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is HeatFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this HeatFlux to another HeatFlux with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A HeatFlux with the specified unit.</returns> + public HeatFlux ToUnit(HeatFluxUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="HeatFlux"/> to another <see cref="HeatFlux"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A HeatFlux with the specified unit.</returns> + public HeatFlux ToUnit(HeatFluxUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(HeatFlux), Unit, typeof(HeatFlux), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (HeatFlux)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="HeatFlux"/> to another <see cref="HeatFlux"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="HeatFlux"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(HeatFluxUnit unit, [NotNullWhen(true)] out HeatFlux? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + HeatFlux? convertedOrNull = (Unit, unit) switch + { + // HeatFluxUnit -> BaseUnit + (HeatFluxUnit.BtuPerHourSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 3.15459075, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.BtuPerMinuteSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.89275445e2, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.BtuPerSecondSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.13565267e4, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.BtuPerSecondSquareInch, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.63533984e6, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.CaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 4.1868e4, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.CentiwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-2d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.DeciwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-1d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.KilocaloriePerHourSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.163, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value * 4.1868e4) * 1e3d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.KilowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e3d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.MicrowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-6d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.MilliwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-3d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.NanowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-9d, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.PoundForcePerFootSecond, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.459390293720636e1, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.PoundPerSecondCubed, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 4.5359237e-1, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.WattPerSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.07639e1, HeatFluxUnit.WattPerSquareMeter), + (HeatFluxUnit.WattPerSquareInch, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.5500031e3, HeatFluxUnit.WattPerSquareMeter), + + // BaseUnit -> HeatFluxUnit + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerHourSquareFoot) => new HeatFlux(_value / 3.15459075, HeatFluxUnit.BtuPerHourSquareFoot), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerMinuteSquareFoot) => new HeatFlux(_value / 1.89275445e2, HeatFluxUnit.BtuPerMinuteSquareFoot), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareFoot) => new HeatFlux(_value / 1.13565267e4, HeatFluxUnit.BtuPerSecondSquareFoot), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareInch) => new HeatFlux(_value / 1.63533984e6, HeatFluxUnit.BtuPerSecondSquareInch), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CaloriePerSecondSquareCentimeter) => new HeatFlux(_value / 4.1868e4, HeatFluxUnit.CaloriePerSecondSquareCentimeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CentiwattPerSquareMeter) => new HeatFlux((_value) / 1e-2d, HeatFluxUnit.CentiwattPerSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.DeciwattPerSquareMeter) => new HeatFlux((_value) / 1e-1d, HeatFluxUnit.DeciwattPerSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerHourSquareMeter) => new HeatFlux(_value / 1.163, HeatFluxUnit.KilocaloriePerHourSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter) => new HeatFlux((_value / 4.1868e4) / 1e3d, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilowattPerSquareMeter) => new HeatFlux((_value) / 1e3d, HeatFluxUnit.KilowattPerSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MicrowattPerSquareMeter) => new HeatFlux((_value) / 1e-6d, HeatFluxUnit.MicrowattPerSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MilliwattPerSquareMeter) => new HeatFlux((_value) / 1e-3d, HeatFluxUnit.MilliwattPerSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.NanowattPerSquareMeter) => new HeatFlux((_value) / 1e-9d, HeatFluxUnit.NanowattPerSquareMeter), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundForcePerFootSecond) => new HeatFlux(_value / 1.459390293720636e1, HeatFluxUnit.PoundForcePerFootSecond), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundPerSecondCubed) => new HeatFlux(_value / 4.5359237e-1, HeatFluxUnit.PoundPerSecondCubed), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareFoot) => new HeatFlux(_value / 1.07639e1, HeatFluxUnit.WattPerSquareFoot), + (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareInch) => new HeatFlux(_value / 1.5500031e3, HeatFluxUnit.WattPerSquareInch), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is HeatFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<HeatFluxUnit> IQuantity<HeatFluxUnit>.ToUnit(HeatFluxUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<HeatFluxUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(HeatFlux)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(HeatFlux)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(HeatFlux)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(HeatFlux)) + return this; + else if (conversionType == typeof(HeatFluxUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return HeatFlux.Info; + else if (conversionType == typeof(BaseDimensions)) + return HeatFlux.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(HeatFlux)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFluxUnit.g.cs b/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFluxUnit.g.cs new file mode 100644 index 0000000000..a03b4d90e6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/HeatFlux/HeatFluxUnit.g.cs @@ -0,0 +1,49 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum HeatFluxUnit + { + BtuPerHourSquareFoot = 1, + BtuPerMinuteSquareFoot = 2, + BtuPerSecondSquareFoot = 3, + BtuPerSecondSquareInch = 4, + CaloriePerSecondSquareCentimeter = 5, + CentiwattPerSquareMeter = 6, + DeciwattPerSquareMeter = 7, + KilocaloriePerHourSquareMeter = 8, + KilocaloriePerSecondSquareCentimeter = 9, + KilowattPerSquareMeter = 10, + MicrowattPerSquareMeter = 11, + MilliwattPerSquareMeter = 12, + NanowattPerSquareMeter = 13, + PoundForcePerFootSecond = 14, + PoundPerSecondCubed = 15, + WattPerSquareFoot = 16, + WattPerSquareInch = 17, + WattPerSquareMeter = 18, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficient.csproj b/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficient.csproj new file mode 100644 index 0000000000..0b6aa1a9e7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficient.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET HeatTransferCoefficient</Title> + <Description>Adds HeatTransferCoefficient units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>heattransfercoefficient unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{3ede821e-ee76-967e-94d7-5b1d1239c8dd}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.HeatTransferCoefficient</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficient.g.cs b/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficient.g.cs new file mode 100644 index 0000000000..85547d1ce5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficient.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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) + /// </summary> + [DataContract] + public readonly partial struct HeatTransferCoefficient : IArithmeticQuantity<HeatTransferCoefficient, HeatTransferCoefficientUnit, double>, IEquatable<HeatTransferCoefficient>, IComparable, IComparable<HeatTransferCoefficient>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly HeatTransferCoefficientUnit? _unit; + + static HeatTransferCoefficient() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); + BaseUnit = HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; + Units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast<HeatTransferCoefficientUnit>().ToArray(); + Zero = new HeatTransferCoefficient(0, BaseUnit); + Info = new QuantityInfo<HeatTransferCoefficientUnit>("HeatTransferCoefficient", + new UnitInfo<HeatTransferCoefficientUnit>[] + { + new UnitInfo<HeatTransferCoefficientUnit>(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, "BtusPerSquareFootDegreeFahrenheit", BaseUnits.Undefined), + new UnitInfo<HeatTransferCoefficientUnit>(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, "WattsPerSquareMeterCelsius", BaseUnits.Undefined), + new UnitInfo<HeatTransferCoefficientUnit>(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, "WattsPerSquareMeterKelvin", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public HeatTransferCoefficient(double value, HeatTransferCoefficientUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="HeatTransferCoefficient" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<HeatTransferCoefficientUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. + /// </summary> + public static HeatTransferCoefficientUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the HeatTransferCoefficient quantity. + /// </summary> + public static HeatTransferCoefficientUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. + /// </summary> + public static HeatTransferCoefficient Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static HeatTransferCoefficient AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<HeatTransferCoefficientUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit"/> + /// </summary> + public double BtusPerSquareFootDegreeFahrenheit => As(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatTransferCoefficientUnit.WattPerSquareMeterCelsius"/> + /// </summary> + public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="HeatTransferCoefficientUnit.WattPerSquareMeterKelvin"/> + /// </summary> + public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: HeatTransferCoefficientUnit -> BaseUnit + unitConverter.SetConversionFunction<HeatTransferCoefficient>(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); + unitConverter.SetConversionFunction<HeatTransferCoefficient>(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<HeatTransferCoefficient>(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> HeatTransferCoefficientUnit + unitConverter.SetConversionFunction<HeatTransferCoefficient>(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit)); + unitConverter.SetConversionFunction<HeatTransferCoefficient>(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"Btu/ft²·hr·°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, new CultureInfo("en-US"), false, true, new string[]{"W/m²·°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, new CultureInfo("en-US"), false, true, new string[]{"W/m²·K"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(HeatTransferCoefficientUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(HeatTransferCoefficientUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="HeatTransferCoefficient"/> from <see cref="HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatTransferCoefficient FromBtusPerSquareFootDegreeFahrenheit(QuantityValue btuspersquarefootdegreefahrenheit) + { + double value = (double) btuspersquarefootdegreefahrenheit; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit); + } + + /// <summary> + /// Creates a <see cref="HeatTransferCoefficient"/> from <see cref="HeatTransferCoefficientUnit.WattPerSquareMeterCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue wattspersquaremetercelsius) + { + double value = (double) wattspersquaremetercelsius; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + } + + /// <summary> + /// Creates a <see cref="HeatTransferCoefficient"/> from <see cref="HeatTransferCoefficientUnit.WattPerSquareMeterKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue wattspersquaremeterkelvin) + { + double value = (double) wattspersquaremeterkelvin; + return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="HeatTransferCoefficientUnit" /> to <see cref="HeatTransferCoefficient" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>HeatTransferCoefficient unit value.</returns> + public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) + { + return new HeatTransferCoefficient((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static HeatTransferCoefficient Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static HeatTransferCoefficient Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<HeatTransferCoefficient, HeatTransferCoefficientUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out HeatTransferCoefficient result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out HeatTransferCoefficient result) + { + return QuantityParser.Default.TryParse<HeatTransferCoefficient, HeatTransferCoefficientUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static HeatTransferCoefficientUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<HeatTransferCoefficientUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.HeatTransferCoefficientUnit)"/> + public static bool TryParseUnit(string str, out HeatTransferCoefficientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out HeatTransferCoefficientUnit unit) + { + return UnitParser.Default.TryParse<HeatTransferCoefficientUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static HeatTransferCoefficient operator -(HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="HeatTransferCoefficient"/> from adding two <see cref="HeatTransferCoefficient"/>.</summary> + public static HeatTransferCoefficient operator +(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="HeatTransferCoefficient"/> from subtracting two <see cref="HeatTransferCoefficient"/>.</summary> + public static HeatTransferCoefficient operator -(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="HeatTransferCoefficient"/> from multiplying value and <see cref="HeatTransferCoefficient"/>.</summary> + public static HeatTransferCoefficient operator *(double left, HeatTransferCoefficient right) + { + return new HeatTransferCoefficient(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="HeatTransferCoefficient"/> from multiplying value and <see cref="HeatTransferCoefficient"/>.</summary> + public static HeatTransferCoefficient operator *(HeatTransferCoefficient left, double right) + { + return new HeatTransferCoefficient(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="HeatTransferCoefficient"/> from dividing <see cref="HeatTransferCoefficient"/> by value.</summary> + public static HeatTransferCoefficient operator /(HeatTransferCoefficient left, double right) + { + return new HeatTransferCoefficient(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="HeatTransferCoefficient"/> by <see cref="HeatTransferCoefficient"/>.</summary> + public static double operator /(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.WattsPerSquareMeterKelvin / right.WattsPerSquareMeterKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="HeatTransferCoefficient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatTransferCoefficient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="HeatTransferCoefficient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatTransferCoefficient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(HeatTransferCoefficient left, HeatTransferCoefficient right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="HeatTransferCoefficient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatTransferCoefficient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is HeatTransferCoefficient otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="HeatTransferCoefficient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(HeatTransferCoefficient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(HeatTransferCoefficient other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="HeatTransferCoefficient"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is HeatTransferCoefficient otherQuantity)) throw new ArgumentException("Expected type HeatTransferCoefficient.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="HeatTransferCoefficient"/> with another <see cref="HeatTransferCoefficient"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(HeatTransferCoefficient other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another HeatTransferCoefficient within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current HeatTransferCoefficient.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(HeatTransferCoefficientUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is HeatTransferCoefficientUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A HeatTransferCoefficient with the specified unit.</returns> + public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="HeatTransferCoefficient"/> to another <see cref="HeatTransferCoefficient"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A HeatTransferCoefficient with the specified unit.</returns> + public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(HeatTransferCoefficient), Unit, typeof(HeatTransferCoefficient), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (HeatTransferCoefficient)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="HeatTransferCoefficient"/> to another <see cref="HeatTransferCoefficient"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="HeatTransferCoefficient"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(HeatTransferCoefficientUnit unit, [NotNullWhen(true)] out HeatTransferCoefficient? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + HeatTransferCoefficient? convertedOrNull = (Unit, unit) switch + { + // HeatTransferCoefficientUnit -> BaseUnit + (HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin) => new HeatTransferCoefficient(_value * 5.6782633411134878, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), + (HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin) => new HeatTransferCoefficient(_value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), + + // BaseUnit -> HeatTransferCoefficientUnit + (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit) => new HeatTransferCoefficient(_value / 5.6782633411134878, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit), + (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius) => new HeatTransferCoefficient(_value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is HeatTransferCoefficientUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<HeatTransferCoefficientUnit> IQuantity<HeatTransferCoefficientUnit>.ToUnit(HeatTransferCoefficientUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<HeatTransferCoefficientUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(HeatTransferCoefficient)) + return this; + else if (conversionType == typeof(HeatTransferCoefficientUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return HeatTransferCoefficient.Info; + else if (conversionType == typeof(BaseDimensions)) + return HeatTransferCoefficient.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficientUnit.g.cs b/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficientUnit.g.cs new file mode 100644 index 0000000000..e337b5095a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/HeatTransferCoefficient/HeatTransferCoefficientUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum HeatTransferCoefficientUnit + { + BtuPerSquareFootDegreeFahrenheit = 1, + WattPerSquareMeterCelsius = 2, + WattPerSquareMeterKelvin = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Illuminance/Illuminance.csproj b/UnitsNet.Modular/GeneratedCode/Illuminance/Illuminance.csproj new file mode 100644 index 0000000000..944ccde98b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Illuminance/Illuminance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Illuminance</Title> + <Description>Adds Illuminance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>illuminance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{d846582b-8ae3-9779-01ea-7210b5330cfd}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Illuminance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Illuminance/Illuminance.g.cs b/UnitsNet.Modular/GeneratedCode/Illuminance/Illuminance.g.cs new file mode 100644 index 0000000000..a5877c8c7a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Illuminance/Illuminance.g.cs @@ -0,0 +1,904 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In photometry, illuminance is the total luminous flux incident on a surface, per unit area. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Illuminance + /// </remarks> + [DataContract] + public readonly partial struct Illuminance : IArithmeticQuantity<Illuminance, IlluminanceUnit, double>, IEquatable<Illuminance>, IComparable, IComparable<Illuminance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly IlluminanceUnit? _unit; + + static Illuminance() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + BaseUnit = IlluminanceUnit.Lux; + Units = Enum.GetValues(typeof(IlluminanceUnit)).Cast<IlluminanceUnit>().ToArray(); + Zero = new Illuminance(0, BaseUnit); + Info = new QuantityInfo<IlluminanceUnit>("Illuminance", + new UnitInfo<IlluminanceUnit>[] + { + new UnitInfo<IlluminanceUnit>(IlluminanceUnit.Kilolux, "Kilolux", BaseUnits.Undefined), + new UnitInfo<IlluminanceUnit>(IlluminanceUnit.Lux, "Lux", BaseUnits.Undefined), + new UnitInfo<IlluminanceUnit>(IlluminanceUnit.Megalux, "Megalux", BaseUnits.Undefined), + new UnitInfo<IlluminanceUnit>(IlluminanceUnit.Millilux, "Millilux", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Illuminance(double value, IlluminanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Illuminance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<IlluminanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Illuminance, which is Lux. All conversions go via this value. + /// </summary> + public static IlluminanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Illuminance quantity. + /// </summary> + public static IlluminanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Lux. + /// </summary> + public static Illuminance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Illuminance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<IlluminanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Illuminance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IlluminanceUnit.Kilolux"/> + /// </summary> + public double Kilolux => As(IlluminanceUnit.Kilolux); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IlluminanceUnit.Lux"/> + /// </summary> + public double Lux => As(IlluminanceUnit.Lux); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IlluminanceUnit.Megalux"/> + /// </summary> + public double Megalux => As(IlluminanceUnit.Megalux); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IlluminanceUnit.Millilux"/> + /// </summary> + public double Millilux => As(IlluminanceUnit.Millilux); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: IlluminanceUnit -> BaseUnit + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Kilolux, IlluminanceUnit.Lux, quantity => quantity.ToUnit(IlluminanceUnit.Lux)); + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Megalux, IlluminanceUnit.Lux, quantity => quantity.ToUnit(IlluminanceUnit.Lux)); + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Millilux, IlluminanceUnit.Lux, quantity => quantity.ToUnit(IlluminanceUnit.Lux)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Lux, IlluminanceUnit.Lux, quantity => quantity); + + // Register in unit converter: BaseUnit -> IlluminanceUnit + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Lux, IlluminanceUnit.Kilolux, quantity => quantity.ToUnit(IlluminanceUnit.Kilolux)); + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Lux, IlluminanceUnit.Megalux, quantity => quantity.ToUnit(IlluminanceUnit.Megalux)); + unitConverter.SetConversionFunction<Illuminance>(IlluminanceUnit.Lux, IlluminanceUnit.Millilux, quantity => quantity.ToUnit(IlluminanceUnit.Millilux)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(IlluminanceUnit.Kilolux, new CultureInfo("en-US"), false, true, new string[]{"klx"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IlluminanceUnit.Lux, new CultureInfo("en-US"), false, true, new string[]{"lx"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IlluminanceUnit.Megalux, new CultureInfo("en-US"), false, true, new string[]{"Mlx"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IlluminanceUnit.Millilux, new CultureInfo("en-US"), false, true, new string[]{"mlx"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(IlluminanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(IlluminanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Illuminance"/> from <see cref="IlluminanceUnit.Kilolux"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Illuminance FromKilolux(QuantityValue kilolux) + { + double value = (double) kilolux; + return new Illuminance(value, IlluminanceUnit.Kilolux); + } + + /// <summary> + /// Creates a <see cref="Illuminance"/> from <see cref="IlluminanceUnit.Lux"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Illuminance FromLux(QuantityValue lux) + { + double value = (double) lux; + return new Illuminance(value, IlluminanceUnit.Lux); + } + + /// <summary> + /// Creates a <see cref="Illuminance"/> from <see cref="IlluminanceUnit.Megalux"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Illuminance FromMegalux(QuantityValue megalux) + { + double value = (double) megalux; + return new Illuminance(value, IlluminanceUnit.Megalux); + } + + /// <summary> + /// Creates a <see cref="Illuminance"/> from <see cref="IlluminanceUnit.Millilux"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Illuminance FromMillilux(QuantityValue millilux) + { + double value = (double) millilux; + return new Illuminance(value, IlluminanceUnit.Millilux); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="IlluminanceUnit" /> to <see cref="Illuminance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Illuminance unit value.</returns> + public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) + { + return new Illuminance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Illuminance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Illuminance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Illuminance, IlluminanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Illuminance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Illuminance result) + { + return QuantityParser.Default.TryParse<Illuminance, IlluminanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static IlluminanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static IlluminanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<IlluminanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.IlluminanceUnit)"/> + public static bool TryParseUnit(string str, out IlluminanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out IlluminanceUnit unit) + { + return UnitParser.Default.TryParse<IlluminanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Illuminance operator -(Illuminance right) + { + return new Illuminance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Illuminance"/> from adding two <see cref="Illuminance"/>.</summary> + public static Illuminance operator +(Illuminance left, Illuminance right) + { + return new Illuminance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Illuminance"/> from subtracting two <see cref="Illuminance"/>.</summary> + public static Illuminance operator -(Illuminance left, Illuminance right) + { + return new Illuminance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Illuminance"/> from multiplying value and <see cref="Illuminance"/>.</summary> + public static Illuminance operator *(double left, Illuminance right) + { + return new Illuminance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Illuminance"/> from multiplying value and <see cref="Illuminance"/>.</summary> + public static Illuminance operator *(Illuminance left, double right) + { + return new Illuminance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Illuminance"/> from dividing <see cref="Illuminance"/> by value.</summary> + public static Illuminance operator /(Illuminance left, double right) + { + return new Illuminance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Illuminance"/> by <see cref="Illuminance"/>.</summary> + public static double operator /(Illuminance left, Illuminance right) + { + return left.Lux / right.Lux; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Illuminance left, Illuminance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Illuminance left, Illuminance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Illuminance left, Illuminance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Illuminance left, Illuminance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Illuminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Illuminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Illuminance left, Illuminance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Illuminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Illuminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Illuminance left, Illuminance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Illuminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Illuminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Illuminance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Illuminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Illuminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Illuminance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Illuminance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Illuminance otherQuantity)) throw new ArgumentException("Expected type Illuminance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Illuminance"/> with another <see cref="Illuminance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Illuminance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Illuminance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Illuminance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(IlluminanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is IlluminanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Illuminance to another Illuminance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Illuminance with the specified unit.</returns> + public Illuminance ToUnit(IlluminanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Illuminance"/> to another <see cref="Illuminance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Illuminance with the specified unit.</returns> + public Illuminance ToUnit(IlluminanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Illuminance), Unit, typeof(Illuminance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Illuminance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Illuminance"/> to another <see cref="Illuminance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Illuminance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(IlluminanceUnit unit, [NotNullWhen(true)] out Illuminance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Illuminance? convertedOrNull = (Unit, unit) switch + { + // IlluminanceUnit -> BaseUnit + (IlluminanceUnit.Kilolux, IlluminanceUnit.Lux) => new Illuminance((_value) * 1e3d, IlluminanceUnit.Lux), + (IlluminanceUnit.Megalux, IlluminanceUnit.Lux) => new Illuminance((_value) * 1e6d, IlluminanceUnit.Lux), + (IlluminanceUnit.Millilux, IlluminanceUnit.Lux) => new Illuminance((_value) * 1e-3d, IlluminanceUnit.Lux), + + // BaseUnit -> IlluminanceUnit + (IlluminanceUnit.Lux, IlluminanceUnit.Kilolux) => new Illuminance((_value) / 1e3d, IlluminanceUnit.Kilolux), + (IlluminanceUnit.Lux, IlluminanceUnit.Megalux) => new Illuminance((_value) / 1e6d, IlluminanceUnit.Megalux), + (IlluminanceUnit.Lux, IlluminanceUnit.Millilux) => new Illuminance((_value) / 1e-3d, IlluminanceUnit.Millilux), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is IlluminanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<IlluminanceUnit> IQuantity<IlluminanceUnit>.ToUnit(IlluminanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<IlluminanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Illuminance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Illuminance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Illuminance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Illuminance)) + return this; + else if (conversionType == typeof(IlluminanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Illuminance.Info; + else if (conversionType == typeof(BaseDimensions)) + return Illuminance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Illuminance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Illuminance/IlluminanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Illuminance/IlluminanceUnit.g.cs new file mode 100644 index 0000000000..7675a53867 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Illuminance/IlluminanceUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum IlluminanceUnit + { + Kilolux = 1, + Lux = 2, + Megalux = 3, + Millilux = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Information/Information.csproj b/UnitsNet.Modular/GeneratedCode/Information/Information.csproj new file mode 100644 index 0000000000..b6fbd1c9c0 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Information/Information.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Information</Title> + <Description>Adds Information units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>information unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{12bab01c-845f-82c9-b00b-a3639cdfb2ce}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Information</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Information/Information.g.cs b/UnitsNet.Modular/GeneratedCode/Information/Information.g.cs new file mode 100644 index 0000000000..d094c1f29e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Information/Information.g.cs @@ -0,0 +1,1371 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. + /// </summary> + [DataContract] + public readonly partial struct Information : IArithmeticQuantity<Information, InformationUnit, decimal>, IDecimalQuantity, IEquatable<Information>, IComparable, IComparable<Information>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly decimal _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly InformationUnit? _unit; + + static Information() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = InformationUnit.Bit; + Units = Enum.GetValues(typeof(InformationUnit)).Cast<InformationUnit>().ToArray(); + Zero = new Information(0, BaseUnit); + Info = new QuantityInfo<InformationUnit>("Information", + new UnitInfo<InformationUnit>[] + { + new UnitInfo<InformationUnit>(InformationUnit.Bit, "Bits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Byte, "Bytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Exabit, "Exabits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Exabyte, "Exabytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Exbibit, "Exbibits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Exbibyte, "Exbibytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Gibibit, "Gibibits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Gibibyte, "Gibibytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Gigabit, "Gigabits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Gigabyte, "Gigabytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Kibibit, "Kibibits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Kibibyte, "Kibibytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Kilobit, "Kilobits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Kilobyte, "Kilobytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Mebibit, "Mebibits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Mebibyte, "Mebibytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Megabit, "Megabits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Megabyte, "Megabytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Pebibit, "Pebibits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Pebibyte, "Pebibytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Petabit, "Petabits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Petabyte, "Petabytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Tebibit, "Tebibits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Tebibyte, "Tebibytes", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Terabit, "Terabits", BaseUnits.Undefined), + new UnitInfo<InformationUnit>(InformationUnit.Terabyte, "Terabytes", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Information(decimal value, InformationUnit unit) + { + _value = value; + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Information" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<InformationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Information, which is Bit. All conversions go via this value. + /// </summary> + public static InformationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Information quantity. + /// </summary> + public static InformationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Bit. + /// </summary> + public static Information Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Information AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public decimal Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + /// <inheritdoc cref="IDecimalQuantity.Value"/> + decimal IDecimalQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<InformationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Information.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Bit"/> + /// </summary> + public decimal Bits => As(InformationUnit.Bit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Byte"/> + /// </summary> + public decimal Bytes => As(InformationUnit.Byte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Exabit"/> + /// </summary> + public decimal Exabits => As(InformationUnit.Exabit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Exabyte"/> + /// </summary> + public decimal Exabytes => As(InformationUnit.Exabyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Exbibit"/> + /// </summary> + public decimal Exbibits => As(InformationUnit.Exbibit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Exbibyte"/> + /// </summary> + public decimal Exbibytes => As(InformationUnit.Exbibyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Gibibit"/> + /// </summary> + public decimal Gibibits => As(InformationUnit.Gibibit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Gibibyte"/> + /// </summary> + public decimal Gibibytes => As(InformationUnit.Gibibyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Gigabit"/> + /// </summary> + public decimal Gigabits => As(InformationUnit.Gigabit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Gigabyte"/> + /// </summary> + public decimal Gigabytes => As(InformationUnit.Gigabyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Kibibit"/> + /// </summary> + public decimal Kibibits => As(InformationUnit.Kibibit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Kibibyte"/> + /// </summary> + public decimal Kibibytes => As(InformationUnit.Kibibyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Kilobit"/> + /// </summary> + public decimal Kilobits => As(InformationUnit.Kilobit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Kilobyte"/> + /// </summary> + public decimal Kilobytes => As(InformationUnit.Kilobyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Mebibit"/> + /// </summary> + public decimal Mebibits => As(InformationUnit.Mebibit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Mebibyte"/> + /// </summary> + public decimal Mebibytes => As(InformationUnit.Mebibyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Megabit"/> + /// </summary> + public decimal Megabits => As(InformationUnit.Megabit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Megabyte"/> + /// </summary> + public decimal Megabytes => As(InformationUnit.Megabyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Pebibit"/> + /// </summary> + public decimal Pebibits => As(InformationUnit.Pebibit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Pebibyte"/> + /// </summary> + public decimal Pebibytes => As(InformationUnit.Pebibyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Petabit"/> + /// </summary> + public decimal Petabits => As(InformationUnit.Petabit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Petabyte"/> + /// </summary> + public decimal Petabytes => As(InformationUnit.Petabyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Tebibit"/> + /// </summary> + public decimal Tebibits => As(InformationUnit.Tebibit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Tebibyte"/> + /// </summary> + public decimal Tebibytes => As(InformationUnit.Tebibyte); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Terabit"/> + /// </summary> + public decimal Terabits => As(InformationUnit.Terabit); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="InformationUnit.Terabyte"/> + /// </summary> + public decimal Terabytes => As(InformationUnit.Terabyte); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: InformationUnit -> BaseUnit + unitConverter.SetConversionFunction<Information>(InformationUnit.Byte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Exabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Exabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Exbibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Exbibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Gibibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Gibibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Gigabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Gigabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Kibibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Kibibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Kilobit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Kilobyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Mebibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Mebibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Megabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Megabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Pebibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Pebibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Petabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Petabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Tebibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Tebibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Terabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Terabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Bit, quantity => quantity); + + // Register in unit converter: BaseUnit -> InformationUnit + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Byte, quantity => quantity.ToUnit(InformationUnit.Byte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Exabit, quantity => quantity.ToUnit(InformationUnit.Exabit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Exabyte, quantity => quantity.ToUnit(InformationUnit.Exabyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Exbibit, quantity => quantity.ToUnit(InformationUnit.Exbibit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Exbibyte, quantity => quantity.ToUnit(InformationUnit.Exbibyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Gibibit, quantity => quantity.ToUnit(InformationUnit.Gibibit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Gibibyte, quantity => quantity.ToUnit(InformationUnit.Gibibyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Gigabit, quantity => quantity.ToUnit(InformationUnit.Gigabit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Gigabyte, quantity => quantity.ToUnit(InformationUnit.Gigabyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Kibibit, quantity => quantity.ToUnit(InformationUnit.Kibibit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Kibibyte, quantity => quantity.ToUnit(InformationUnit.Kibibyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Kilobit, quantity => quantity.ToUnit(InformationUnit.Kilobit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Kilobyte, quantity => quantity.ToUnit(InformationUnit.Kilobyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Mebibit, quantity => quantity.ToUnit(InformationUnit.Mebibit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Mebibyte, quantity => quantity.ToUnit(InformationUnit.Mebibyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Megabit, quantity => quantity.ToUnit(InformationUnit.Megabit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Megabyte, quantity => quantity.ToUnit(InformationUnit.Megabyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Pebibit, quantity => quantity.ToUnit(InformationUnit.Pebibit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Pebibyte, quantity => quantity.ToUnit(InformationUnit.Pebibyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Petabit, quantity => quantity.ToUnit(InformationUnit.Petabit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Petabyte, quantity => quantity.ToUnit(InformationUnit.Petabyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Tebibit, quantity => quantity.ToUnit(InformationUnit.Tebibit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Tebibyte, quantity => quantity.ToUnit(InformationUnit.Tebibyte)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Terabit, quantity => quantity.ToUnit(InformationUnit.Terabit)); + unitConverter.SetConversionFunction<Information>(InformationUnit.Bit, InformationUnit.Terabyte, quantity => quantity.ToUnit(InformationUnit.Terabyte)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Bit, new CultureInfo("en-US"), false, true, new string[]{"b"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Byte, new CultureInfo("en-US"), false, true, new string[]{"B"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Exabit, new CultureInfo("en-US"), false, true, new string[]{"Eb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Exabyte, new CultureInfo("en-US"), false, true, new string[]{"EB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Exbibit, new CultureInfo("en-US"), false, true, new string[]{"Eib"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Exbibyte, new CultureInfo("en-US"), false, true, new string[]{"EiB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Gibibit, new CultureInfo("en-US"), false, true, new string[]{"Gib"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Gibibyte, new CultureInfo("en-US"), false, true, new string[]{"GiB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Gigabit, new CultureInfo("en-US"), false, true, new string[]{"Gb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Gigabyte, new CultureInfo("en-US"), false, true, new string[]{"GB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Kibibit, new CultureInfo("en-US"), false, true, new string[]{"Kib"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Kibibyte, new CultureInfo("en-US"), false, true, new string[]{"KiB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Kilobit, new CultureInfo("en-US"), false, true, new string[]{"kb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Kilobyte, new CultureInfo("en-US"), false, true, new string[]{"kB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Mebibit, new CultureInfo("en-US"), false, true, new string[]{"Mib"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Mebibyte, new CultureInfo("en-US"), false, true, new string[]{"MiB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Megabit, new CultureInfo("en-US"), false, true, new string[]{"Mb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Megabyte, new CultureInfo("en-US"), false, true, new string[]{"MB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Pebibit, new CultureInfo("en-US"), false, true, new string[]{"Pib"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Pebibyte, new CultureInfo("en-US"), false, true, new string[]{"PiB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Petabit, new CultureInfo("en-US"), false, true, new string[]{"Pb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Petabyte, new CultureInfo("en-US"), false, true, new string[]{"PB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Tebibit, new CultureInfo("en-US"), false, true, new string[]{"Tib"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Tebibyte, new CultureInfo("en-US"), false, true, new string[]{"TiB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Terabit, new CultureInfo("en-US"), false, true, new string[]{"Tb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(InformationUnit.Terabyte, new CultureInfo("en-US"), false, true, new string[]{"TB"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(InformationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(InformationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Bit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromBits(QuantityValue bits) + { + decimal value = (decimal) bits; + return new Information(value, InformationUnit.Bit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Byte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromBytes(QuantityValue bytes) + { + decimal value = (decimal) bytes; + return new Information(value, InformationUnit.Byte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Exabit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromExabits(QuantityValue exabits) + { + decimal value = (decimal) exabits; + return new Information(value, InformationUnit.Exabit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Exabyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromExabytes(QuantityValue exabytes) + { + decimal value = (decimal) exabytes; + return new Information(value, InformationUnit.Exabyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Exbibit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromExbibits(QuantityValue exbibits) + { + decimal value = (decimal) exbibits; + return new Information(value, InformationUnit.Exbibit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Exbibyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromExbibytes(QuantityValue exbibytes) + { + decimal value = (decimal) exbibytes; + return new Information(value, InformationUnit.Exbibyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Gibibit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromGibibits(QuantityValue gibibits) + { + decimal value = (decimal) gibibits; + return new Information(value, InformationUnit.Gibibit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Gibibyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromGibibytes(QuantityValue gibibytes) + { + decimal value = (decimal) gibibytes; + return new Information(value, InformationUnit.Gibibyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Gigabit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromGigabits(QuantityValue gigabits) + { + decimal value = (decimal) gigabits; + return new Information(value, InformationUnit.Gigabit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Gigabyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromGigabytes(QuantityValue gigabytes) + { + decimal value = (decimal) gigabytes; + return new Information(value, InformationUnit.Gigabyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Kibibit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromKibibits(QuantityValue kibibits) + { + decimal value = (decimal) kibibits; + return new Information(value, InformationUnit.Kibibit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Kibibyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromKibibytes(QuantityValue kibibytes) + { + decimal value = (decimal) kibibytes; + return new Information(value, InformationUnit.Kibibyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Kilobit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromKilobits(QuantityValue kilobits) + { + decimal value = (decimal) kilobits; + return new Information(value, InformationUnit.Kilobit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Kilobyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromKilobytes(QuantityValue kilobytes) + { + decimal value = (decimal) kilobytes; + return new Information(value, InformationUnit.Kilobyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Mebibit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromMebibits(QuantityValue mebibits) + { + decimal value = (decimal) mebibits; + return new Information(value, InformationUnit.Mebibit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Mebibyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromMebibytes(QuantityValue mebibytes) + { + decimal value = (decimal) mebibytes; + return new Information(value, InformationUnit.Mebibyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Megabit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromMegabits(QuantityValue megabits) + { + decimal value = (decimal) megabits; + return new Information(value, InformationUnit.Megabit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Megabyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromMegabytes(QuantityValue megabytes) + { + decimal value = (decimal) megabytes; + return new Information(value, InformationUnit.Megabyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Pebibit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromPebibits(QuantityValue pebibits) + { + decimal value = (decimal) pebibits; + return new Information(value, InformationUnit.Pebibit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Pebibyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromPebibytes(QuantityValue pebibytes) + { + decimal value = (decimal) pebibytes; + return new Information(value, InformationUnit.Pebibyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Petabit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromPetabits(QuantityValue petabits) + { + decimal value = (decimal) petabits; + return new Information(value, InformationUnit.Petabit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Petabyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromPetabytes(QuantityValue petabytes) + { + decimal value = (decimal) petabytes; + return new Information(value, InformationUnit.Petabyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Tebibit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromTebibits(QuantityValue tebibits) + { + decimal value = (decimal) tebibits; + return new Information(value, InformationUnit.Tebibit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Tebibyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromTebibytes(QuantityValue tebibytes) + { + decimal value = (decimal) tebibytes; + return new Information(value, InformationUnit.Tebibyte); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Terabit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromTerabits(QuantityValue terabits) + { + decimal value = (decimal) terabits; + return new Information(value, InformationUnit.Terabit); + } + + /// <summary> + /// Creates a <see cref="Information"/> from <see cref="InformationUnit.Terabyte"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Information FromTerabytes(QuantityValue terabytes) + { + decimal value = (decimal) terabytes; + return new Information(value, InformationUnit.Terabyte); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="InformationUnit" /> to <see cref="Information" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Information unit value.</returns> + public static Information From(QuantityValue value, InformationUnit fromUnit) + { + return new Information((decimal)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Information Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Information Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Information, InformationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Information result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Information result) + { + return QuantityParser.Default.TryParse<Information, InformationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static InformationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static InformationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<InformationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.InformationUnit)"/> + public static bool TryParseUnit(string str, out InformationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out InformationUnit unit) + { + return UnitParser.Default.TryParse<InformationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Information operator -(Information right) + { + return new Information(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Information"/> from adding two <see cref="Information"/>.</summary> + public static Information operator +(Information left, Information right) + { + return new Information(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Information"/> from subtracting two <see cref="Information"/>.</summary> + public static Information operator -(Information left, Information right) + { + return new Information(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Information"/> from multiplying value and <see cref="Information"/>.</summary> + public static Information operator *(decimal left, Information right) + { + return new Information(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Information"/> from multiplying value and <see cref="Information"/>.</summary> + public static Information operator *(Information left, decimal right) + { + return new Information(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Information"/> from dividing <see cref="Information"/> by value.</summary> + public static Information operator /(Information left, decimal right) + { + return new Information(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Information"/> by <see cref="Information"/>.</summary> + public static decimal operator /(Information left, Information right) + { + return left.Bits / right.Bits; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Information left, Information right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Information left, Information right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Information left, Information right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Information left, Information right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Information"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Information, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Information left, Information right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Information"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Information, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Information left, Information right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Information"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Information, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Information otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Information"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Information, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Information other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Information"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Information otherQuantity)) throw new ArgumentException("Expected type Information.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Information"/> with another <see cref="Information"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Information other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Information within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using decimal internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Information other, decimal tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + decimal thisValue = this.Value; + decimal otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Information.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public decimal As(InformationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + double IQuantity<InformationUnit>.As(InformationUnit unit) + { + return (double)As(unit); + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is InformationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Information to another Information with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Information with the specified unit.</returns> + public Information ToUnit(InformationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Information"/> to another <see cref="Information"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Information with the specified unit.</returns> + public Information ToUnit(InformationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Information), Unit, typeof(Information), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Information)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Information"/> to another <see cref="Information"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Information"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(InformationUnit unit, [NotNullWhen(true)] out Information? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Information? convertedOrNull = (Unit, unit) switch + { + // InformationUnit -> BaseUnit + (InformationUnit.Byte, InformationUnit.Bit) => new Information(_value * 8m, InformationUnit.Bit), + (InformationUnit.Exabit, InformationUnit.Bit) => new Information((_value) * 1e18m, InformationUnit.Bit), + (InformationUnit.Exabyte, InformationUnit.Bit) => new Information((_value * 8m) * 1e18m, InformationUnit.Bit), + (InformationUnit.Exbibit, InformationUnit.Bit) => new Information((_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Exbibyte, InformationUnit.Bit) => new Information((_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Gibibit, InformationUnit.Bit) => new Information((_value) * (1024m * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Gibibyte, InformationUnit.Bit) => new Information((_value * 8m) * (1024m * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Gigabit, InformationUnit.Bit) => new Information((_value) * 1e9m, InformationUnit.Bit), + (InformationUnit.Gigabyte, InformationUnit.Bit) => new Information((_value * 8m) * 1e9m, InformationUnit.Bit), + (InformationUnit.Kibibit, InformationUnit.Bit) => new Information((_value) * 1024m, InformationUnit.Bit), + (InformationUnit.Kibibyte, InformationUnit.Bit) => new Information((_value * 8m) * 1024m, InformationUnit.Bit), + (InformationUnit.Kilobit, InformationUnit.Bit) => new Information((_value) * 1e3m, InformationUnit.Bit), + (InformationUnit.Kilobyte, InformationUnit.Bit) => new Information((_value * 8m) * 1e3m, InformationUnit.Bit), + (InformationUnit.Mebibit, InformationUnit.Bit) => new Information((_value) * (1024m * 1024), InformationUnit.Bit), + (InformationUnit.Mebibyte, InformationUnit.Bit) => new Information((_value * 8m) * (1024m * 1024), InformationUnit.Bit), + (InformationUnit.Megabit, InformationUnit.Bit) => new Information((_value) * 1e6m, InformationUnit.Bit), + (InformationUnit.Megabyte, InformationUnit.Bit) => new Information((_value * 8m) * 1e6m, InformationUnit.Bit), + (InformationUnit.Pebibit, InformationUnit.Bit) => new Information((_value) * (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Pebibyte, InformationUnit.Bit) => new Information((_value * 8m) * (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Petabit, InformationUnit.Bit) => new Information((_value) * 1e15m, InformationUnit.Bit), + (InformationUnit.Petabyte, InformationUnit.Bit) => new Information((_value * 8m) * 1e15m, InformationUnit.Bit), + (InformationUnit.Tebibit, InformationUnit.Bit) => new Information((_value) * (1024m * 1024 * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Tebibyte, InformationUnit.Bit) => new Information((_value * 8m) * (1024m * 1024 * 1024 * 1024), InformationUnit.Bit), + (InformationUnit.Terabit, InformationUnit.Bit) => new Information((_value) * 1e12m, InformationUnit.Bit), + (InformationUnit.Terabyte, InformationUnit.Bit) => new Information((_value * 8m) * 1e12m, InformationUnit.Bit), + + // BaseUnit -> InformationUnit + (InformationUnit.Bit, InformationUnit.Byte) => new Information(_value / 8m, InformationUnit.Byte), + (InformationUnit.Bit, InformationUnit.Exabit) => new Information((_value) / 1e18m, InformationUnit.Exabit), + (InformationUnit.Bit, InformationUnit.Exabyte) => new Information((_value / 8m) / 1e18m, InformationUnit.Exabyte), + (InformationUnit.Bit, InformationUnit.Exbibit) => new Information((_value) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbibit), + (InformationUnit.Bit, InformationUnit.Exbibyte) => new Information((_value / 8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbibyte), + (InformationUnit.Bit, InformationUnit.Gibibit) => new Information((_value) / (1024m * 1024 * 1024), InformationUnit.Gibibit), + (InformationUnit.Bit, InformationUnit.Gibibyte) => new Information((_value / 8m) / (1024m * 1024 * 1024), InformationUnit.Gibibyte), + (InformationUnit.Bit, InformationUnit.Gigabit) => new Information((_value) / 1e9m, InformationUnit.Gigabit), + (InformationUnit.Bit, InformationUnit.Gigabyte) => new Information((_value / 8m) / 1e9m, InformationUnit.Gigabyte), + (InformationUnit.Bit, InformationUnit.Kibibit) => new Information((_value) / 1024m, InformationUnit.Kibibit), + (InformationUnit.Bit, InformationUnit.Kibibyte) => new Information((_value / 8m) / 1024m, InformationUnit.Kibibyte), + (InformationUnit.Bit, InformationUnit.Kilobit) => new Information((_value) / 1e3m, InformationUnit.Kilobit), + (InformationUnit.Bit, InformationUnit.Kilobyte) => new Information((_value / 8m) / 1e3m, InformationUnit.Kilobyte), + (InformationUnit.Bit, InformationUnit.Mebibit) => new Information((_value) / (1024m * 1024), InformationUnit.Mebibit), + (InformationUnit.Bit, InformationUnit.Mebibyte) => new Information((_value / 8m) / (1024m * 1024), InformationUnit.Mebibyte), + (InformationUnit.Bit, InformationUnit.Megabit) => new Information((_value) / 1e6m, InformationUnit.Megabit), + (InformationUnit.Bit, InformationUnit.Megabyte) => new Information((_value / 8m) / 1e6m, InformationUnit.Megabyte), + (InformationUnit.Bit, InformationUnit.Pebibit) => new Information((_value) / (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebibit), + (InformationUnit.Bit, InformationUnit.Pebibyte) => new Information((_value / 8m) / (1024m * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebibyte), + (InformationUnit.Bit, InformationUnit.Petabit) => new Information((_value) / 1e15m, InformationUnit.Petabit), + (InformationUnit.Bit, InformationUnit.Petabyte) => new Information((_value / 8m) / 1e15m, InformationUnit.Petabyte), + (InformationUnit.Bit, InformationUnit.Tebibit) => new Information((_value) / (1024m * 1024 * 1024 * 1024), InformationUnit.Tebibit), + (InformationUnit.Bit, InformationUnit.Tebibyte) => new Information((_value / 8m) / (1024m * 1024 * 1024 * 1024), InformationUnit.Tebibyte), + (InformationUnit.Bit, InformationUnit.Terabit) => new Information((_value) / 1e12m, InformationUnit.Terabit), + (InformationUnit.Bit, InformationUnit.Terabyte) => new Information((_value / 8m) / 1e12m, InformationUnit.Terabyte), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is InformationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<InformationUnit> IQuantity<InformationUnit>.ToUnit(InformationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<InformationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Information)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Information)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Information)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Information)) + return this; + else if (conversionType == typeof(InformationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Information.Info; + else if (conversionType == typeof(BaseDimensions)) + return Information.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Information)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Information/InformationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Information/InformationUnit.g.cs new file mode 100644 index 0000000000..fd72b621c2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Information/InformationUnit.g.cs @@ -0,0 +1,57 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum InformationUnit + { + Bit = 1, + Byte = 2, + Exabit = 3, + Exabyte = 4, + Exbibit = 5, + Exbibyte = 6, + Gibibit = 7, + Gibibyte = 8, + Gigabit = 9, + Gigabyte = 10, + Kibibit = 11, + Kibibyte = 12, + Kilobit = 13, + Kilobyte = 14, + Mebibit = 15, + Mebibyte = 16, + Megabit = 17, + Megabyte = 18, + Pebibit = 19, + Pebibyte = 20, + Petabit = 21, + Petabyte = 22, + Tebibit = 23, + Tebibyte = 24, + Terabit = 25, + Terabyte = 26, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Irradiance/Irradiance.csproj b/UnitsNet.Modular/GeneratedCode/Irradiance/Irradiance.csproj new file mode 100644 index 0000000000..048c4484ab --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Irradiance/Irradiance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Irradiance</Title> + <Description>Adds Irradiance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>irradiance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5f9c09c7-9e32-8927-7a5d-90001ceffc69}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Irradiance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Irradiance/Irradiance.g.cs b/UnitsNet.Modular/GeneratedCode/Irradiance/Irradiance.g.cs new file mode 100644 index 0000000000..7f236e3225 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Irradiance/Irradiance.g.cs @@ -0,0 +1,1111 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. + /// </summary> + [DataContract] + public readonly partial struct Irradiance : IArithmeticQuantity<Irradiance, IrradianceUnit, double>, IEquatable<Irradiance>, IComparable, IComparable<Irradiance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly IrradianceUnit? _unit; + + static Irradiance() + { + BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + BaseUnit = IrradianceUnit.WattPerSquareMeter; + Units = Enum.GetValues(typeof(IrradianceUnit)).Cast<IrradianceUnit>().ToArray(); + Zero = new Irradiance(0, BaseUnit); + Info = new QuantityInfo<IrradianceUnit>("Irradiance", + new UnitInfo<IrradianceUnit>[] + { + new UnitInfo<IrradianceUnit>(IrradianceUnit.KilowattPerSquareCentimeter, "KilowattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.KilowattPerSquareMeter, "KilowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.MegawattPerSquareCentimeter, "MegawattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.MegawattPerSquareMeter, "MegawattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.MicrowattPerSquareCentimeter, "MicrowattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.MicrowattPerSquareMeter, "MicrowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.MilliwattPerSquareCentimeter, "MilliwattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.MilliwattPerSquareMeter, "MilliwattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.NanowattPerSquareCentimeter, "NanowattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.NanowattPerSquareMeter, "NanowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.PicowattPerSquareCentimeter, "PicowattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.PicowattPerSquareMeter, "PicowattsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.WattPerSquareCentimeter, "WattsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradianceUnit>(IrradianceUnit.WattPerSquareMeter, "WattsPerSquareMeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Irradiance(double value, IrradianceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Irradiance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<IrradianceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. + /// </summary> + public static IrradianceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Irradiance quantity. + /// </summary> + public static IrradianceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. + /// </summary> + public static Irradiance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Irradiance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<IrradianceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Irradiance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.KilowattPerSquareCentimeter"/> + /// </summary> + public double KilowattsPerSquareCentimeter => As(IrradianceUnit.KilowattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.KilowattPerSquareMeter"/> + /// </summary> + public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.MegawattPerSquareCentimeter"/> + /// </summary> + public double MegawattsPerSquareCentimeter => As(IrradianceUnit.MegawattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.MegawattPerSquareMeter"/> + /// </summary> + public double MegawattsPerSquareMeter => As(IrradianceUnit.MegawattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.MicrowattPerSquareCentimeter"/> + /// </summary> + public double MicrowattsPerSquareCentimeter => As(IrradianceUnit.MicrowattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.MicrowattPerSquareMeter"/> + /// </summary> + public double MicrowattsPerSquareMeter => As(IrradianceUnit.MicrowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.MilliwattPerSquareCentimeter"/> + /// </summary> + public double MilliwattsPerSquareCentimeter => As(IrradianceUnit.MilliwattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.MilliwattPerSquareMeter"/> + /// </summary> + public double MilliwattsPerSquareMeter => As(IrradianceUnit.MilliwattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.NanowattPerSquareCentimeter"/> + /// </summary> + public double NanowattsPerSquareCentimeter => As(IrradianceUnit.NanowattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.NanowattPerSquareMeter"/> + /// </summary> + public double NanowattsPerSquareMeter => As(IrradianceUnit.NanowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.PicowattPerSquareCentimeter"/> + /// </summary> + public double PicowattsPerSquareCentimeter => As(IrradianceUnit.PicowattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.PicowattPerSquareMeter"/> + /// </summary> + public double PicowattsPerSquareMeter => As(IrradianceUnit.PicowattPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.WattPerSquareCentimeter"/> + /// </summary> + public double WattsPerSquareCentimeter => As(IrradianceUnit.WattPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradianceUnit.WattPerSquareMeter"/> + /// </summary> + public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: IrradianceUnit -> BaseUnit + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.KilowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.KilowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.MegawattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.MegawattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.MicrowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.MicrowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.MilliwattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.MilliwattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.NanowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.NanowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.PicowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.PicowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> IrradianceUnit + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.KilowattPerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.KilowattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MegawattPerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MegawattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MicrowattPerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MicrowattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MilliwattPerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MilliwattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.NanowattPerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.NanowattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.PicowattPerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.PicowattPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiance>(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareCentimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.KilowattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kW/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.KilowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.MegawattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"MW/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.MegawattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"MW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.MicrowattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"µW/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.MicrowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"µW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.MilliwattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mW/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.MilliwattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"mW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.NanowattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"nW/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.NanowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"nW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.PicowattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"pW/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.PicowattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"pW/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.WattPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"W/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradianceUnit.WattPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"W/m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(IrradianceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(IrradianceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.KilowattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromKilowattsPerSquareCentimeter(QuantityValue kilowattspersquarecentimeter) + { + double value = (double) kilowattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.KilowattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.KilowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) + { + double value = (double) kilowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.MegawattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromMegawattsPerSquareCentimeter(QuantityValue megawattspersquarecentimeter) + { + double value = (double) megawattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.MegawattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.MegawattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromMegawattsPerSquareMeter(QuantityValue megawattspersquaremeter) + { + double value = (double) megawattspersquaremeter; + return new Irradiance(value, IrradianceUnit.MegawattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.MicrowattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromMicrowattsPerSquareCentimeter(QuantityValue microwattspersquarecentimeter) + { + double value = (double) microwattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.MicrowattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.MicrowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromMicrowattsPerSquareMeter(QuantityValue microwattspersquaremeter) + { + double value = (double) microwattspersquaremeter; + return new Irradiance(value, IrradianceUnit.MicrowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.MilliwattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromMilliwattsPerSquareCentimeter(QuantityValue milliwattspersquarecentimeter) + { + double value = (double) milliwattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.MilliwattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.MilliwattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromMilliwattsPerSquareMeter(QuantityValue milliwattspersquaremeter) + { + double value = (double) milliwattspersquaremeter; + return new Irradiance(value, IrradianceUnit.MilliwattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.NanowattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromNanowattsPerSquareCentimeter(QuantityValue nanowattspersquarecentimeter) + { + double value = (double) nanowattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.NanowattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.NanowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromNanowattsPerSquareMeter(QuantityValue nanowattspersquaremeter) + { + double value = (double) nanowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.NanowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.PicowattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromPicowattsPerSquareCentimeter(QuantityValue picowattspersquarecentimeter) + { + double value = (double) picowattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.PicowattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.PicowattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromPicowattsPerSquareMeter(QuantityValue picowattspersquaremeter) + { + double value = (double) picowattspersquaremeter; + return new Irradiance(value, IrradianceUnit.PicowattPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.WattPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromWattsPerSquareCentimeter(QuantityValue wattspersquarecentimeter) + { + double value = (double) wattspersquarecentimeter; + return new Irradiance(value, IrradianceUnit.WattPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiance"/> from <see cref="IrradianceUnit.WattPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) + { + double value = (double) wattspersquaremeter; + return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="IrradianceUnit" /> to <see cref="Irradiance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Irradiance unit value.</returns> + public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) + { + return new Irradiance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Irradiance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Irradiance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Irradiance, IrradianceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Irradiance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Irradiance result) + { + return QuantityParser.Default.TryParse<Irradiance, IrradianceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static IrradianceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static IrradianceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<IrradianceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.IrradianceUnit)"/> + public static bool TryParseUnit(string str, out IrradianceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out IrradianceUnit unit) + { + return UnitParser.Default.TryParse<IrradianceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Irradiance operator -(Irradiance right) + { + return new Irradiance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Irradiance"/> from adding two <see cref="Irradiance"/>.</summary> + public static Irradiance operator +(Irradiance left, Irradiance right) + { + return new Irradiance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Irradiance"/> from subtracting two <see cref="Irradiance"/>.</summary> + public static Irradiance operator -(Irradiance left, Irradiance right) + { + return new Irradiance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Irradiance"/> from multiplying value and <see cref="Irradiance"/>.</summary> + public static Irradiance operator *(double left, Irradiance right) + { + return new Irradiance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Irradiance"/> from multiplying value and <see cref="Irradiance"/>.</summary> + public static Irradiance operator *(Irradiance left, double right) + { + return new Irradiance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Irradiance"/> from dividing <see cref="Irradiance"/> by value.</summary> + public static Irradiance operator /(Irradiance left, double right) + { + return new Irradiance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Irradiance"/> by <see cref="Irradiance"/>.</summary> + public static double operator /(Irradiance left, Irradiance right) + { + return left.WattsPerSquareMeter / right.WattsPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Irradiance left, Irradiance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Irradiance left, Irradiance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Irradiance left, Irradiance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Irradiance left, Irradiance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Irradiance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Irradiance left, Irradiance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Irradiance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Irradiance left, Irradiance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Irradiance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Irradiance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Irradiance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Irradiance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Irradiance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Irradiance otherQuantity)) throw new ArgumentException("Expected type Irradiance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Irradiance"/> with another <see cref="Irradiance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Irradiance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Irradiance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Irradiance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(IrradianceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is IrradianceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Irradiance to another Irradiance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Irradiance with the specified unit.</returns> + public Irradiance ToUnit(IrradianceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Irradiance"/> to another <see cref="Irradiance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Irradiance with the specified unit.</returns> + public Irradiance ToUnit(IrradianceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Irradiance), Unit, typeof(Irradiance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Irradiance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Irradiance"/> to another <see cref="Irradiance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Irradiance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(IrradianceUnit unit, [NotNullWhen(true)] out Irradiance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Irradiance? convertedOrNull = (Unit, unit) switch + { + // IrradianceUnit -> BaseUnit + (IrradianceUnit.KilowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e3d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.KilowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e3d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.MegawattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e6d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.MegawattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e6d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.MicrowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-6d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.MicrowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-6d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.MilliwattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-3d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.MilliwattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-3d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.NanowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-9d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.NanowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-9d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.PicowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-12d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.PicowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-12d, IrradianceUnit.WattPerSquareMeter), + (IrradianceUnit.WattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance(_value * 10000, IrradianceUnit.WattPerSquareMeter), + + // BaseUnit -> IrradianceUnit + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e3d, IrradianceUnit.KilowattPerSquareCentimeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareMeter) => new Irradiance((_value) / 1e3d, IrradianceUnit.KilowattPerSquareMeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e6d, IrradianceUnit.MegawattPerSquareCentimeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareMeter) => new Irradiance((_value) / 1e6d, IrradianceUnit.MegawattPerSquareMeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-6d, IrradianceUnit.MicrowattPerSquareCentimeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareMeter) => new Irradiance((_value) / 1e-6d, IrradianceUnit.MicrowattPerSquareMeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-3d, IrradianceUnit.MilliwattPerSquareCentimeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareMeter) => new Irradiance((_value) / 1e-3d, IrradianceUnit.MilliwattPerSquareMeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-9d, IrradianceUnit.NanowattPerSquareCentimeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareMeter) => new Irradiance((_value) / 1e-9d, IrradianceUnit.NanowattPerSquareMeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-12d, IrradianceUnit.PicowattPerSquareCentimeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareMeter) => new Irradiance((_value) / 1e-12d, IrradianceUnit.PicowattPerSquareMeter), + (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareCentimeter) => new Irradiance(_value * 0.0001, IrradianceUnit.WattPerSquareCentimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is IrradianceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<IrradianceUnit> IQuantity<IrradianceUnit>.ToUnit(IrradianceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<IrradianceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Irradiance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Irradiance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Irradiance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Irradiance)) + return this; + else if (conversionType == typeof(IrradianceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Irradiance.Info; + else if (conversionType == typeof(BaseDimensions)) + return Irradiance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Irradiance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Irradiance/IrradianceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Irradiance/IrradianceUnit.g.cs new file mode 100644 index 0000000000..2ed5f09b06 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Irradiance/IrradianceUnit.g.cs @@ -0,0 +1,45 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum IrradianceUnit + { + KilowattPerSquareCentimeter = 1, + KilowattPerSquareMeter = 2, + MegawattPerSquareCentimeter = 3, + MegawattPerSquareMeter = 4, + MicrowattPerSquareCentimeter = 5, + MicrowattPerSquareMeter = 6, + MilliwattPerSquareCentimeter = 7, + MilliwattPerSquareMeter = 8, + NanowattPerSquareCentimeter = 9, + NanowattPerSquareMeter = 10, + PicowattPerSquareCentimeter = 11, + PicowattPerSquareMeter = 12, + WattPerSquareCentimeter = 13, + WattPerSquareMeter = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Irradiation/Irradiation.csproj b/UnitsNet.Modular/GeneratedCode/Irradiation/Irradiation.csproj new file mode 100644 index 0000000000..13c4ced95b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Irradiation/Irradiation.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Irradiation</Title> + <Description>Adds Irradiation units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>irradiation unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{b545726f-7a83-3c78-2b55-6a709c5a6d00}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Irradiation</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Irradiation/Irradiation.g.cs b/UnitsNet.Modular/GeneratedCode/Irradiation/Irradiation.g.cs new file mode 100644 index 0000000000..5e0867d655 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Irradiation/Irradiation.g.cs @@ -0,0 +1,967 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Irradiation + /// </remarks> + [DataContract] + public readonly partial struct Irradiation : IArithmeticQuantity<Irradiation, IrradiationUnit, double>, IEquatable<Irradiation>, IComparable, IComparable<Irradiation>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly IrradiationUnit? _unit; + + static Irradiation() + { + BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + BaseUnit = IrradiationUnit.JoulePerSquareMeter; + Units = Enum.GetValues(typeof(IrradiationUnit)).Cast<IrradiationUnit>().ToArray(); + Zero = new Irradiation(0, BaseUnit); + Info = new QuantityInfo<IrradiationUnit>("Irradiation", + new UnitInfo<IrradiationUnit>[] + { + new UnitInfo<IrradiationUnit>(IrradiationUnit.JoulePerSquareCentimeter, "JoulesPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradiationUnit>(IrradiationUnit.JoulePerSquareMeter, "JoulesPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradiationUnit>(IrradiationUnit.JoulePerSquareMillimeter, "JoulesPerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<IrradiationUnit>(IrradiationUnit.KilojoulePerSquareMeter, "KilojoulesPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradiationUnit>(IrradiationUnit.KilowattHourPerSquareMeter, "KilowattHoursPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<IrradiationUnit>(IrradiationUnit.MillijoulePerSquareCentimeter, "MillijoulesPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<IrradiationUnit>(IrradiationUnit.WattHourPerSquareMeter, "WattHoursPerSquareMeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Irradiation(double value, IrradiationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Irradiation" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<IrradiationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. + /// </summary> + public static IrradiationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Irradiation quantity. + /// </summary> + public static IrradiationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. + /// </summary> + public static Irradiation Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Irradiation AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<IrradiationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Irradiation.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.JoulePerSquareCentimeter"/> + /// </summary> + public double JoulesPerSquareCentimeter => As(IrradiationUnit.JoulePerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.JoulePerSquareMeter"/> + /// </summary> + public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.JoulePerSquareMillimeter"/> + /// </summary> + public double JoulesPerSquareMillimeter => As(IrradiationUnit.JoulePerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.KilojoulePerSquareMeter"/> + /// </summary> + public double KilojoulesPerSquareMeter => As(IrradiationUnit.KilojoulePerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.KilowattHourPerSquareMeter"/> + /// </summary> + public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.MillijoulePerSquareCentimeter"/> + /// </summary> + public double MillijoulesPerSquareCentimeter => As(IrradiationUnit.MillijoulePerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="IrradiationUnit.WattHourPerSquareMeter"/> + /// </summary> + public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: IrradiationUnit -> BaseUnit + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMillimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.KilojoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.KilowattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.MillijoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.WattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> IrradiationUnit + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareCentimeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMillimeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMillimeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilojoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.KilojoulePerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilowattHourPerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.KilowattHourPerSquareMeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.MillijoulePerSquareCentimeter, quantity => quantity.ToUnit(IrradiationUnit.MillijoulePerSquareCentimeter)); + unitConverter.SetConversionFunction<Irradiation>(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.WattHourPerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.WattHourPerSquareMeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.JoulePerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"J/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.JoulePerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"J/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.JoulePerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"J/mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.KilojoulePerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kJ/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.KilowattHourPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kWh/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.MillijoulePerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mJ/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(IrradiationUnit.WattHourPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"Wh/m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(IrradiationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(IrradiationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.JoulePerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromJoulesPerSquareCentimeter(QuantityValue joulespersquarecentimeter) + { + double value = (double) joulespersquarecentimeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.JoulePerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) + { + double value = (double) joulespersquaremeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.JoulePerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromJoulesPerSquareMillimeter(QuantityValue joulespersquaremillimeter) + { + double value = (double) joulespersquaremillimeter; + return new Irradiation(value, IrradiationUnit.JoulePerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.KilojoulePerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromKilojoulesPerSquareMeter(QuantityValue kilojoulespersquaremeter) + { + double value = (double) kilojoulespersquaremeter; + return new Irradiation(value, IrradiationUnit.KilojoulePerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.KilowattHourPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) + { + double value = (double) kilowatthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.MillijoulePerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromMillijoulesPerSquareCentimeter(QuantityValue millijoulespersquarecentimeter) + { + double value = (double) millijoulespersquarecentimeter; + return new Irradiation(value, IrradiationUnit.MillijoulePerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Irradiation"/> from <see cref="IrradiationUnit.WattHourPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) + { + double value = (double) watthourspersquaremeter; + return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="IrradiationUnit" /> to <see cref="Irradiation" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Irradiation unit value.</returns> + public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) + { + return new Irradiation((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Irradiation Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Irradiation Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Irradiation, IrradiationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Irradiation result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Irradiation result) + { + return QuantityParser.Default.TryParse<Irradiation, IrradiationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static IrradiationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static IrradiationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<IrradiationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.IrradiationUnit)"/> + public static bool TryParseUnit(string str, out IrradiationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out IrradiationUnit unit) + { + return UnitParser.Default.TryParse<IrradiationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Irradiation operator -(Irradiation right) + { + return new Irradiation(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Irradiation"/> from adding two <see cref="Irradiation"/>.</summary> + public static Irradiation operator +(Irradiation left, Irradiation right) + { + return new Irradiation(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Irradiation"/> from subtracting two <see cref="Irradiation"/>.</summary> + public static Irradiation operator -(Irradiation left, Irradiation right) + { + return new Irradiation(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Irradiation"/> from multiplying value and <see cref="Irradiation"/>.</summary> + public static Irradiation operator *(double left, Irradiation right) + { + return new Irradiation(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Irradiation"/> from multiplying value and <see cref="Irradiation"/>.</summary> + public static Irradiation operator *(Irradiation left, double right) + { + return new Irradiation(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Irradiation"/> from dividing <see cref="Irradiation"/> by value.</summary> + public static Irradiation operator /(Irradiation left, double right) + { + return new Irradiation(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Irradiation"/> by <see cref="Irradiation"/>.</summary> + public static double operator /(Irradiation left, Irradiation right) + { + return left.JoulesPerSquareMeter / right.JoulesPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Irradiation left, Irradiation right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Irradiation left, Irradiation right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Irradiation left, Irradiation right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Irradiation left, Irradiation right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Irradiation"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiation, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Irradiation left, Irradiation right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Irradiation"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiation, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Irradiation left, Irradiation right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Irradiation"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiation, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Irradiation otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Irradiation"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Irradiation, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Irradiation other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Irradiation"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Irradiation otherQuantity)) throw new ArgumentException("Expected type Irradiation.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Irradiation"/> with another <see cref="Irradiation"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Irradiation other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Irradiation within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Irradiation.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(IrradiationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is IrradiationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Irradiation to another Irradiation with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Irradiation with the specified unit.</returns> + public Irradiation ToUnit(IrradiationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Irradiation"/> to another <see cref="Irradiation"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Irradiation with the specified unit.</returns> + public Irradiation ToUnit(IrradiationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Irradiation), Unit, typeof(Irradiation), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Irradiation)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Irradiation"/> to another <see cref="Irradiation"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Irradiation"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(IrradiationUnit unit, [NotNullWhen(true)] out Irradiation? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Irradiation? convertedOrNull = (Unit, unit) switch + { + // IrradiationUnit -> BaseUnit + (IrradiationUnit.JoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 1e4, IrradiationUnit.JoulePerSquareMeter), + (IrradiationUnit.JoulePerSquareMillimeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 1e6, IrradiationUnit.JoulePerSquareMeter), + (IrradiationUnit.KilojoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value) * 1e3d, IrradiationUnit.JoulePerSquareMeter), + (IrradiationUnit.KilowattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value * 3600d) * 1e3d, IrradiationUnit.JoulePerSquareMeter), + (IrradiationUnit.MillijoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value * 1e4) * 1e-3d, IrradiationUnit.JoulePerSquareMeter), + (IrradiationUnit.WattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 3600d, IrradiationUnit.JoulePerSquareMeter), + + // BaseUnit -> IrradiationUnit + (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareCentimeter) => new Irradiation(_value / 1e4, IrradiationUnit.JoulePerSquareCentimeter), + (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMillimeter) => new Irradiation(_value / 1e6, IrradiationUnit.JoulePerSquareMillimeter), + (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilojoulePerSquareMeter) => new Irradiation((_value) / 1e3d, IrradiationUnit.KilojoulePerSquareMeter), + (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilowattHourPerSquareMeter) => new Irradiation((_value / 3600d) / 1e3d, IrradiationUnit.KilowattHourPerSquareMeter), + (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.MillijoulePerSquareCentimeter) => new Irradiation((_value / 1e4) / 1e-3d, IrradiationUnit.MillijoulePerSquareCentimeter), + (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.WattHourPerSquareMeter) => new Irradiation(_value / 3600d, IrradiationUnit.WattHourPerSquareMeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is IrradiationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<IrradiationUnit> IQuantity<IrradiationUnit>.ToUnit(IrradiationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<IrradiationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Irradiation)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Irradiation)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Irradiation)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Irradiation)) + return this; + else if (conversionType == typeof(IrradiationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Irradiation.Info; + else if (conversionType == typeof(BaseDimensions)) + return Irradiation.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Irradiation)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Irradiation/IrradiationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Irradiation/IrradiationUnit.g.cs new file mode 100644 index 0000000000..449fdf2491 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Irradiation/IrradiationUnit.g.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum IrradiationUnit + { + JoulePerSquareCentimeter = 1, + JoulePerSquareMeter = 2, + JoulePerSquareMillimeter = 3, + KilojoulePerSquareMeter = 4, + KilowattHourPerSquareMeter = 5, + MillijoulePerSquareCentimeter = 6, + WattHourPerSquareMeter = 7, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Jerk/Jerk.csproj b/UnitsNet.Modular/GeneratedCode/Jerk/Jerk.csproj new file mode 100644 index 0000000000..0cc2571be0 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Jerk/Jerk.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Jerk</Title> + <Description>Adds Jerk units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>jerk unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8540cfb1-fe4a-dcc3-a70e-840262803cfc}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Jerk</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Jerk/Jerk.g.cs b/UnitsNet.Modular/GeneratedCode/Jerk/Jerk.g.cs new file mode 100644 index 0000000000..9da28b3d63 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Jerk/Jerk.g.cs @@ -0,0 +1,1059 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + [DataContract] + public readonly partial struct Jerk : IArithmeticQuantity<Jerk, JerkUnit, double>, IEquatable<Jerk>, IComparable, IComparable<Jerk>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly JerkUnit? _unit; + + static Jerk() + { + BaseDimensions = new BaseDimensions(1, 0, -3, 0, 0, 0, 0); + BaseUnit = JerkUnit.MeterPerSecondCubed; + Units = Enum.GetValues(typeof(JerkUnit)).Cast<JerkUnit>().ToArray(); + Zero = new Jerk(0, BaseUnit); + Info = new QuantityInfo<JerkUnit>("Jerk", + new UnitInfo<JerkUnit>[] + { + new UnitInfo<JerkUnit>(JerkUnit.CentimeterPerSecondCubed, "CentimetersPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.DecimeterPerSecondCubed, "DecimetersPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.FootPerSecondCubed, "FeetPerSecondCubed", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)), + new UnitInfo<JerkUnit>(JerkUnit.InchPerSecondCubed, "InchesPerSecondCubed", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second)), + new UnitInfo<JerkUnit>(JerkUnit.KilometerPerSecondCubed, "KilometersPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.MeterPerSecondCubed, "MetersPerSecondCubed", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), + new UnitInfo<JerkUnit>(JerkUnit.MicrometerPerSecondCubed, "MicrometersPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.MillimeterPerSecondCubed, "MillimetersPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.MillistandardGravitiesPerSecond, "MillistandardGravitiesPerSecond", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.NanometerPerSecondCubed, "NanometersPerSecondCubed", BaseUnits.Undefined), + new UnitInfo<JerkUnit>(JerkUnit.StandardGravitiesPerSecond, "StandardGravitiesPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Jerk(double value, JerkUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Jerk" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<JerkUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Jerk, which is MeterPerSecondCubed. All conversions go via this value. + /// </summary> + public static JerkUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Jerk quantity. + /// </summary> + public static JerkUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondCubed. + /// </summary> + public static Jerk Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Jerk AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public JerkUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<JerkUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Jerk.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.CentimeterPerSecondCubed"/> + /// </summary> + public double CentimetersPerSecondCubed => As(JerkUnit.CentimeterPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.DecimeterPerSecondCubed"/> + /// </summary> + public double DecimetersPerSecondCubed => As(JerkUnit.DecimeterPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.FootPerSecondCubed"/> + /// </summary> + public double FeetPerSecondCubed => As(JerkUnit.FootPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.InchPerSecondCubed"/> + /// </summary> + public double InchesPerSecondCubed => As(JerkUnit.InchPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.KilometerPerSecondCubed"/> + /// </summary> + public double KilometersPerSecondCubed => As(JerkUnit.KilometerPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.MeterPerSecondCubed"/> + /// </summary> + public double MetersPerSecondCubed => As(JerkUnit.MeterPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.MicrometerPerSecondCubed"/> + /// </summary> + public double MicrometersPerSecondCubed => As(JerkUnit.MicrometerPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.MillimeterPerSecondCubed"/> + /// </summary> + public double MillimetersPerSecondCubed => As(JerkUnit.MillimeterPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.MillistandardGravitiesPerSecond"/> + /// </summary> + public double MillistandardGravitiesPerSecond => As(JerkUnit.MillistandardGravitiesPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.NanometerPerSecondCubed"/> + /// </summary> + public double NanometersPerSecondCubed => As(JerkUnit.NanometerPerSecondCubed); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="JerkUnit.StandardGravitiesPerSecond"/> + /// </summary> + public double StandardGravitiesPerSecond => As(JerkUnit.StandardGravitiesPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: JerkUnit -> BaseUnit + unitConverter.SetConversionFunction<Jerk>(JerkUnit.CentimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.DecimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.FootPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.InchPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.KilometerPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MicrometerPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MillimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MillistandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.NanometerPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.StandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity); + + // Register in unit converter: BaseUnit -> JerkUnit + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.CentimeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.CentimeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.DecimeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.DecimeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.FootPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.FootPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.InchPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.InchPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.KilometerPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.KilometerPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.MicrometerPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MicrometerPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.MillimeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MillimeterPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.MillistandardGravitiesPerSecond, quantity => quantity.ToUnit(JerkUnit.MillistandardGravitiesPerSecond)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.NanometerPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.NanometerPerSecondCubed)); + unitConverter.SetConversionFunction<Jerk>(JerkUnit.MeterPerSecondCubed, JerkUnit.StandardGravitiesPerSecond, quantity => quantity.ToUnit(JerkUnit.StandardGravitiesPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.CentimeterPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"cm/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.CentimeterPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"см/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.DecimeterPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"dm/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.DecimeterPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"дм/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.FootPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"ft/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.FootPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"фут/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.InchPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"in/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.InchPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"дюйм/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.KilometerPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"km/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.KilometerPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"км/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MeterPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"m/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MeterPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"м/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MicrometerPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"µm/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MicrometerPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"мкм/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MillimeterPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"mm/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MillimeterPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"мм/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MillistandardGravitiesPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.MillistandardGravitiesPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.NanometerPerSecondCubed, new CultureInfo("en-US"), false, true, new string[]{"nm/s³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.NanometerPerSecondCubed, new CultureInfo("ru-RU"), false, true, new string[]{"нм/с³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.StandardGravitiesPerSecond, new CultureInfo("en-US"), false, true, new string[]{"g/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(JerkUnit.StandardGravitiesPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"g/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(JerkUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(JerkUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.CentimeterPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromCentimetersPerSecondCubed(QuantityValue centimeterspersecondcubed) + { + double value = (double) centimeterspersecondcubed; + return new Jerk(value, JerkUnit.CentimeterPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.DecimeterPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromDecimetersPerSecondCubed(QuantityValue decimeterspersecondcubed) + { + double value = (double) decimeterspersecondcubed; + return new Jerk(value, JerkUnit.DecimeterPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.FootPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromFeetPerSecondCubed(QuantityValue feetpersecondcubed) + { + double value = (double) feetpersecondcubed; + return new Jerk(value, JerkUnit.FootPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.InchPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromInchesPerSecondCubed(QuantityValue inchespersecondcubed) + { + double value = (double) inchespersecondcubed; + return new Jerk(value, JerkUnit.InchPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.KilometerPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromKilometersPerSecondCubed(QuantityValue kilometerspersecondcubed) + { + double value = (double) kilometerspersecondcubed; + return new Jerk(value, JerkUnit.KilometerPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.MeterPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromMetersPerSecondCubed(QuantityValue meterspersecondcubed) + { + double value = (double) meterspersecondcubed; + return new Jerk(value, JerkUnit.MeterPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.MicrometerPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromMicrometersPerSecondCubed(QuantityValue micrometerspersecondcubed) + { + double value = (double) micrometerspersecondcubed; + return new Jerk(value, JerkUnit.MicrometerPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.MillimeterPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromMillimetersPerSecondCubed(QuantityValue millimeterspersecondcubed) + { + double value = (double) millimeterspersecondcubed; + return new Jerk(value, JerkUnit.MillimeterPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.MillistandardGravitiesPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromMillistandardGravitiesPerSecond(QuantityValue millistandardgravitiespersecond) + { + double value = (double) millistandardgravitiespersecond; + return new Jerk(value, JerkUnit.MillistandardGravitiesPerSecond); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.NanometerPerSecondCubed"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromNanometersPerSecondCubed(QuantityValue nanometerspersecondcubed) + { + double value = (double) nanometerspersecondcubed; + return new Jerk(value, JerkUnit.NanometerPerSecondCubed); + } + + /// <summary> + /// Creates a <see cref="Jerk"/> from <see cref="JerkUnit.StandardGravitiesPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Jerk FromStandardGravitiesPerSecond(QuantityValue standardgravitiespersecond) + { + double value = (double) standardgravitiespersecond; + return new Jerk(value, JerkUnit.StandardGravitiesPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="JerkUnit" /> to <see cref="Jerk" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Jerk unit value.</returns> + public static Jerk From(QuantityValue value, JerkUnit fromUnit) + { + return new Jerk((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Jerk Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Jerk Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Jerk, JerkUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Jerk result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Jerk result) + { + return QuantityParser.Default.TryParse<Jerk, JerkUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static JerkUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static JerkUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<JerkUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.JerkUnit)"/> + public static bool TryParseUnit(string str, out JerkUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out JerkUnit unit) + { + return UnitParser.Default.TryParse<JerkUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Jerk operator -(Jerk right) + { + return new Jerk(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Jerk"/> from adding two <see cref="Jerk"/>.</summary> + public static Jerk operator +(Jerk left, Jerk right) + { + return new Jerk(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Jerk"/> from subtracting two <see cref="Jerk"/>.</summary> + public static Jerk operator -(Jerk left, Jerk right) + { + return new Jerk(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Jerk"/> from multiplying value and <see cref="Jerk"/>.</summary> + public static Jerk operator *(double left, Jerk right) + { + return new Jerk(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Jerk"/> from multiplying value and <see cref="Jerk"/>.</summary> + public static Jerk operator *(Jerk left, double right) + { + return new Jerk(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Jerk"/> from dividing <see cref="Jerk"/> by value.</summary> + public static Jerk operator /(Jerk left, double right) + { + return new Jerk(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Jerk"/> by <see cref="Jerk"/>.</summary> + public static double operator /(Jerk left, Jerk right) + { + return left.MetersPerSecondCubed / right.MetersPerSecondCubed; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Jerk left, Jerk right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Jerk left, Jerk right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Jerk left, Jerk right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Jerk left, Jerk right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Jerk"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Jerk, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Jerk left, Jerk right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Jerk"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Jerk, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Jerk left, Jerk right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Jerk"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Jerk, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Jerk otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Jerk"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Jerk, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Jerk other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Jerk"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Jerk otherQuantity)) throw new ArgumentException("Expected type Jerk.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Jerk"/> with another <see cref="Jerk"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Jerk other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Jerk within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Jerk other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Jerk.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(JerkUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is JerkUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(JerkUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Jerk to another Jerk with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Jerk with the specified unit.</returns> + public Jerk ToUnit(JerkUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Jerk"/> to another <see cref="Jerk"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Jerk with the specified unit.</returns> + public Jerk ToUnit(JerkUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Jerk), Unit, typeof(Jerk), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Jerk)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Jerk"/> to another <see cref="Jerk"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Jerk"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(JerkUnit unit, [NotNullWhen(true)] out Jerk? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Jerk? convertedOrNull = (Unit, unit) switch + { + // JerkUnit -> BaseUnit + (JerkUnit.CentimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-2d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.DecimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-1d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.FootPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk(_value * 0.304800, JerkUnit.MeterPerSecondCubed), + (JerkUnit.InchPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk(_value * 0.0254, JerkUnit.MeterPerSecondCubed), + (JerkUnit.KilometerPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e3d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.MicrometerPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-6d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.MillimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-3d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.MillistandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed) => new Jerk((_value * 9.80665) * 1e-3d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.NanometerPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-9d, JerkUnit.MeterPerSecondCubed), + (JerkUnit.StandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed) => new Jerk(_value * 9.80665, JerkUnit.MeterPerSecondCubed), + + // BaseUnit -> JerkUnit + (JerkUnit.MeterPerSecondCubed, JerkUnit.CentimeterPerSecondCubed) => new Jerk((_value) / 1e-2d, JerkUnit.CentimeterPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.DecimeterPerSecondCubed) => new Jerk((_value) / 1e-1d, JerkUnit.DecimeterPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.FootPerSecondCubed) => new Jerk(_value / 0.304800, JerkUnit.FootPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.InchPerSecondCubed) => new Jerk(_value / 0.0254, JerkUnit.InchPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.KilometerPerSecondCubed) => new Jerk((_value) / 1e3d, JerkUnit.KilometerPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.MicrometerPerSecondCubed) => new Jerk((_value) / 1e-6d, JerkUnit.MicrometerPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.MillimeterPerSecondCubed) => new Jerk((_value) / 1e-3d, JerkUnit.MillimeterPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.MillistandardGravitiesPerSecond) => new Jerk((_value / 9.80665) / 1e-3d, JerkUnit.MillistandardGravitiesPerSecond), + (JerkUnit.MeterPerSecondCubed, JerkUnit.NanometerPerSecondCubed) => new Jerk((_value) / 1e-9d, JerkUnit.NanometerPerSecondCubed), + (JerkUnit.MeterPerSecondCubed, JerkUnit.StandardGravitiesPerSecond) => new Jerk(_value / 9.80665, JerkUnit.StandardGravitiesPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is JerkUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(JerkUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<JerkUnit> IQuantity<JerkUnit>.ToUnit(JerkUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<JerkUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Jerk)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Jerk)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Jerk)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Jerk)) + return this; + else if (conversionType == typeof(JerkUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Jerk.Info; + else if (conversionType == typeof(BaseDimensions)) + return Jerk.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Jerk)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Jerk/JerkUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Jerk/JerkUnit.g.cs new file mode 100644 index 0000000000..e269a35497 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Jerk/JerkUnit.g.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum JerkUnit + { + CentimeterPerSecondCubed = 1, + DecimeterPerSecondCubed = 2, + FootPerSecondCubed = 3, + InchPerSecondCubed = 4, + KilometerPerSecondCubed = 5, + MeterPerSecondCubed = 6, + MicrometerPerSecondCubed = 7, + MillimeterPerSecondCubed = 8, + MillistandardGravitiesPerSecond = 9, + NanometerPerSecondCubed = 10, + StandardGravitiesPerSecond = 11, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosity.csproj b/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosity.csproj new file mode 100644 index 0000000000..455ef4a570 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET KinematicViscosity</Title> + <Description>Adds KinematicViscosity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>kinematicviscosity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{733e533d-9ff2-4c72-3da9-200f758dc6e3}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.KinematicViscosity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosity.g.cs b/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosity.g.cs new file mode 100644 index 0000000000..e8a6df26f7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosity.g.cs @@ -0,0 +1,1017 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress. + /// </summary> + /// <remarks> + /// http://en.wikipedia.org/wiki/Viscosity + /// </remarks> + [DataContract] + public readonly partial struct KinematicViscosity : IArithmeticQuantity<KinematicViscosity, KinematicViscosityUnit, double>, IEquatable<KinematicViscosity>, IComparable, IComparable<KinematicViscosity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly KinematicViscosityUnit? _unit; + + static KinematicViscosity() + { + BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); + BaseUnit = KinematicViscosityUnit.SquareMeterPerSecond; + Units = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast<KinematicViscosityUnit>().ToArray(); + Zero = new KinematicViscosity(0, BaseUnit); + Info = new QuantityInfo<KinematicViscosityUnit>("KinematicViscosity", + new UnitInfo<KinematicViscosityUnit>[] + { + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Centistokes, "Centistokes", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Decistokes, "Decistokes", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Kilostokes, "Kilostokes", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Microstokes, "Microstokes", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Millistokes, "Millistokes", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Nanostokes, "Nanostokes", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.SquareFootPerSecond, "SquareFeetPerSecond", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.SquareMeterPerSecond, "SquareMetersPerSecond", BaseUnits.Undefined), + new UnitInfo<KinematicViscosityUnit>(KinematicViscosityUnit.Stokes, "Stokes", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public KinematicViscosity(double value, KinematicViscosityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="KinematicViscosity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<KinematicViscosityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. + /// </summary> + public static KinematicViscosityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the KinematicViscosity quantity. + /// </summary> + public static KinematicViscosityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. + /// </summary> + public static KinematicViscosity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static KinematicViscosity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<KinematicViscosityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Centistokes"/> + /// </summary> + public double Centistokes => As(KinematicViscosityUnit.Centistokes); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Decistokes"/> + /// </summary> + public double Decistokes => As(KinematicViscosityUnit.Decistokes); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Kilostokes"/> + /// </summary> + public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Microstokes"/> + /// </summary> + public double Microstokes => As(KinematicViscosityUnit.Microstokes); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Millistokes"/> + /// </summary> + public double Millistokes => As(KinematicViscosityUnit.Millistokes); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Nanostokes"/> + /// </summary> + public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.SquareFootPerSecond"/> + /// </summary> + public double SquareFeetPerSecond => As(KinematicViscosityUnit.SquareFootPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.SquareMeterPerSecond"/> + /// </summary> + public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="KinematicViscosityUnit.Stokes"/> + /// </summary> + public double Stokes => As(KinematicViscosityUnit.Stokes); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: KinematicViscosityUnit -> BaseUnit + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Centistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Decistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Kilostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Microstokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Millistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Nanostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareFootPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.Stokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> KinematicViscosityUnit + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Centistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Centistokes)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Decistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Decistokes)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Kilostokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Kilostokes)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Microstokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Microstokes)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Millistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Millistokes)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Nanostokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Nanostokes)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareFootPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareFootPerSecond)); + unitConverter.SetConversionFunction<KinematicViscosity>(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Stokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Stokes)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Centistokes, new CultureInfo("en-US"), false, true, new string[]{"cSt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Centistokes, new CultureInfo("ru-RU"), false, true, new string[]{"сСт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Decistokes, new CultureInfo("en-US"), false, true, new string[]{"dSt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Decistokes, new CultureInfo("ru-RU"), false, true, new string[]{"дСт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Kilostokes, new CultureInfo("en-US"), false, true, new string[]{"kSt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Kilostokes, new CultureInfo("ru-RU"), false, true, new string[]{"кСт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Microstokes, new CultureInfo("en-US"), false, true, new string[]{"µSt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Microstokes, new CultureInfo("ru-RU"), false, true, new string[]{"мкСт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Millistokes, new CultureInfo("en-US"), false, true, new string[]{"mSt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Millistokes, new CultureInfo("ru-RU"), false, true, new string[]{"мСт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Nanostokes, new CultureInfo("en-US"), false, true, new string[]{"nSt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Nanostokes, new CultureInfo("ru-RU"), false, true, new string[]{"нСт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.SquareFootPerSecond, new CultureInfo("en-US"), false, true, new string[]{"ft²/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.SquareMeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"m²/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.SquareMeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"м²/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Stokes, new CultureInfo("en-US"), false, true, new string[]{"St"}); + unitAbbreviationsCache.PerformAbbreviationMapping(KinematicViscosityUnit.Stokes, new CultureInfo("ru-RU"), false, true, new string[]{"Ст"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(KinematicViscosityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(KinematicViscosityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Centistokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromCentistokes(QuantityValue centistokes) + { + double value = (double) centistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Decistokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromDecistokes(QuantityValue decistokes) + { + double value = (double) decistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Kilostokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) + { + double value = (double) kilostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Microstokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) + { + double value = (double) microstokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Millistokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromMillistokes(QuantityValue millistokes) + { + double value = (double) millistokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Nanostokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) + { + double value = (double) nanostokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.SquareFootPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromSquareFeetPerSecond(QuantityValue squarefeetpersecond) + { + double value = (double) squarefeetpersecond; + return new KinematicViscosity(value, KinematicViscosityUnit.SquareFootPerSecond); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.SquareMeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) + { + double value = (double) squaremeterspersecond; + return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="KinematicViscosity"/> from <see cref="KinematicViscosityUnit.Stokes"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static KinematicViscosity FromStokes(QuantityValue stokes) + { + double value = (double) stokes; + return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="KinematicViscosityUnit" /> to <see cref="KinematicViscosity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>KinematicViscosity unit value.</returns> + public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) + { + return new KinematicViscosity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static KinematicViscosity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static KinematicViscosity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<KinematicViscosity, KinematicViscosityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out KinematicViscosity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out KinematicViscosity result) + { + return QuantityParser.Default.TryParse<KinematicViscosity, KinematicViscosityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static KinematicViscosityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static KinematicViscosityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<KinematicViscosityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.KinematicViscosityUnit)"/> + public static bool TryParseUnit(string str, out KinematicViscosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out KinematicViscosityUnit unit) + { + return UnitParser.Default.TryParse<KinematicViscosityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static KinematicViscosity operator -(KinematicViscosity right) + { + return new KinematicViscosity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="KinematicViscosity"/> from adding two <see cref="KinematicViscosity"/>.</summary> + public static KinematicViscosity operator +(KinematicViscosity left, KinematicViscosity right) + { + return new KinematicViscosity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="KinematicViscosity"/> from subtracting two <see cref="KinematicViscosity"/>.</summary> + public static KinematicViscosity operator -(KinematicViscosity left, KinematicViscosity right) + { + return new KinematicViscosity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="KinematicViscosity"/> from multiplying value and <see cref="KinematicViscosity"/>.</summary> + public static KinematicViscosity operator *(double left, KinematicViscosity right) + { + return new KinematicViscosity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="KinematicViscosity"/> from multiplying value and <see cref="KinematicViscosity"/>.</summary> + public static KinematicViscosity operator *(KinematicViscosity left, double right) + { + return new KinematicViscosity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="KinematicViscosity"/> from dividing <see cref="KinematicViscosity"/> by value.</summary> + public static KinematicViscosity operator /(KinematicViscosity left, double right) + { + return new KinematicViscosity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="KinematicViscosity"/> by <see cref="KinematicViscosity"/>.</summary> + public static double operator /(KinematicViscosity left, KinematicViscosity right) + { + return left.SquareMetersPerSecond / right.SquareMetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(KinematicViscosity left, KinematicViscosity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(KinematicViscosity left, KinematicViscosity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(KinematicViscosity left, KinematicViscosity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(KinematicViscosity left, KinematicViscosity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="KinematicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(KinematicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(KinematicViscosity left, KinematicViscosity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="KinematicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(KinematicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(KinematicViscosity left, KinematicViscosity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="KinematicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(KinematicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is KinematicViscosity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="KinematicViscosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(KinematicViscosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(KinematicViscosity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="KinematicViscosity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is KinematicViscosity otherQuantity)) throw new ArgumentException("Expected type KinematicViscosity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="KinematicViscosity"/> with another <see cref="KinematicViscosity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(KinematicViscosity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another KinematicViscosity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current KinematicViscosity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(KinematicViscosityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is KinematicViscosityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A KinematicViscosity with the specified unit.</returns> + public KinematicViscosity ToUnit(KinematicViscosityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="KinematicViscosity"/> to another <see cref="KinematicViscosity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A KinematicViscosity with the specified unit.</returns> + public KinematicViscosity ToUnit(KinematicViscosityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(KinematicViscosity), Unit, typeof(KinematicViscosity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (KinematicViscosity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="KinematicViscosity"/> to another <see cref="KinematicViscosity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="KinematicViscosity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(KinematicViscosityUnit unit, [NotNullWhen(true)] out KinematicViscosity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + KinematicViscosity? convertedOrNull = (Unit, unit) switch + { + // KinematicViscosityUnit -> BaseUnit + (KinematicViscosityUnit.Centistokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-2d, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.Decistokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-1d, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.Kilostokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e3d, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.Microstokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-6d, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.Millistokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-3d, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.Nanostokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-9d, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.SquareFootPerSecond, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity(_value / 10.7639, KinematicViscosityUnit.SquareMeterPerSecond), + (KinematicViscosityUnit.Stokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity(_value / 1e4, KinematicViscosityUnit.SquareMeterPerSecond), + + // BaseUnit -> KinematicViscosityUnit + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Centistokes) => new KinematicViscosity((_value * 1e4) / 1e-2d, KinematicViscosityUnit.Centistokes), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Decistokes) => new KinematicViscosity((_value * 1e4) / 1e-1d, KinematicViscosityUnit.Decistokes), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Kilostokes) => new KinematicViscosity((_value * 1e4) / 1e3d, KinematicViscosityUnit.Kilostokes), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Microstokes) => new KinematicViscosity((_value * 1e4) / 1e-6d, KinematicViscosityUnit.Microstokes), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Millistokes) => new KinematicViscosity((_value * 1e4) / 1e-3d, KinematicViscosityUnit.Millistokes), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Nanostokes) => new KinematicViscosity((_value * 1e4) / 1e-9d, KinematicViscosityUnit.Nanostokes), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareFootPerSecond) => new KinematicViscosity(_value * 10.7639, KinematicViscosityUnit.SquareFootPerSecond), + (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Stokes) => new KinematicViscosity(_value * 1e4, KinematicViscosityUnit.Stokes), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is KinematicViscosityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<KinematicViscosityUnit> IQuantity<KinematicViscosityUnit>.ToUnit(KinematicViscosityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<KinematicViscosityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(KinematicViscosity)) + return this; + else if (conversionType == typeof(KinematicViscosityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return KinematicViscosity.Info; + else if (conversionType == typeof(BaseDimensions)) + return KinematicViscosity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosityUnit.g.cs new file mode 100644 index 0000000000..f01709d0c3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/KinematicViscosity/KinematicViscosityUnit.g.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum KinematicViscosityUnit + { + Centistokes = 1, + Decistokes = 2, + Kilostokes = 3, + Microstokes = 4, + Millistokes = 5, + Nanostokes = 6, + SquareFootPerSecond = 7, + SquareMeterPerSecond = 8, + Stokes = 9, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Length/Length.csproj b/UnitsNet.Modular/GeneratedCode/Length/Length.csproj new file mode 100644 index 0000000000..974f5052bc --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Length/Length.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Length</Title> + <Description>Adds Length units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>length unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{0556c9ad-b3a1-730c-959f-baf21e60f972}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Length</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Length/Length.g.cs b/UnitsNet.Modular/GeneratedCode/Length/Length.g.cs new file mode 100644 index 0000000000..9b00cfaa65 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Length/Length.g.cs @@ -0,0 +1,1605 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units. + /// </summary> + [DataContract] + public readonly partial struct Length : IArithmeticQuantity<Length, LengthUnit, double>, IEquatable<Length>, IComparable, IComparable<Length>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LengthUnit? _unit; + + static Length() + { + BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + BaseUnit = LengthUnit.Meter; + Units = Enum.GetValues(typeof(LengthUnit)).Cast<LengthUnit>().ToArray(); + Zero = new Length(0, BaseUnit); + Info = new QuantityInfo<LengthUnit>("Length", + new UnitInfo<LengthUnit>[] + { + new UnitInfo<LengthUnit>(LengthUnit.Angstrom, "Angstroms", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.AstronomicalUnit, "AstronomicalUnits", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Centimeter, "Centimeters", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Chain, "Chains", new BaseUnits(length: LengthUnit.Chain)), + new UnitInfo<LengthUnit>(LengthUnit.DataMile, "DataMiles", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Decameter, "Decameters", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Decimeter, "Decimeters", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.DtpPica, "DtpPicas", new BaseUnits(length: LengthUnit.DtpPica)), + new UnitInfo<LengthUnit>(LengthUnit.DtpPoint, "DtpPoints", new BaseUnits(length: LengthUnit.DtpPoint)), + new UnitInfo<LengthUnit>(LengthUnit.Fathom, "Fathoms", new BaseUnits(length: LengthUnit.Fathom)), + new UnitInfo<LengthUnit>(LengthUnit.Foot, "Feet", new BaseUnits(length: LengthUnit.Foot)), + new UnitInfo<LengthUnit>(LengthUnit.Hand, "Hands", new BaseUnits(length: LengthUnit.Hand)), + new UnitInfo<LengthUnit>(LengthUnit.Hectometer, "Hectometers", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Inch, "Inches", new BaseUnits(length: LengthUnit.Inch)), + new UnitInfo<LengthUnit>(LengthUnit.KilolightYear, "KilolightYears", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Kilometer, "Kilometers", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Kiloparsec, "Kiloparsecs", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.LightYear, "LightYears", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.MegalightYear, "MegalightYears", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Megaparsec, "Megaparsecs", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Meter, "Meters", new BaseUnits(length: LengthUnit.Meter)), + new UnitInfo<LengthUnit>(LengthUnit.Microinch, "Microinches", new BaseUnits(length: LengthUnit.Microinch)), + new UnitInfo<LengthUnit>(LengthUnit.Micrometer, "Micrometers", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Mil, "Mils", new BaseUnits(length: LengthUnit.Mil)), + new UnitInfo<LengthUnit>(LengthUnit.Mile, "Miles", new BaseUnits(length: LengthUnit.Mile)), + new UnitInfo<LengthUnit>(LengthUnit.Millimeter, "Millimeters", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Nanometer, "Nanometers", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.NauticalMile, "NauticalMiles", new BaseUnits(length: LengthUnit.NauticalMile)), + new UnitInfo<LengthUnit>(LengthUnit.Parsec, "Parsecs", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.PrinterPica, "PrinterPicas", new BaseUnits(length: LengthUnit.PrinterPica)), + new UnitInfo<LengthUnit>(LengthUnit.PrinterPoint, "PrinterPoints", new BaseUnits(length: LengthUnit.PrinterPoint)), + new UnitInfo<LengthUnit>(LengthUnit.Shackle, "Shackles", new BaseUnits(length: LengthUnit.Shackle)), + new UnitInfo<LengthUnit>(LengthUnit.SolarRadius, "SolarRadiuses", BaseUnits.Undefined), + new UnitInfo<LengthUnit>(LengthUnit.Twip, "Twips", new BaseUnits(length: LengthUnit.Twip)), + new UnitInfo<LengthUnit>(LengthUnit.UsSurveyFoot, "UsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)), + new UnitInfo<LengthUnit>(LengthUnit.Yard, "Yards", new BaseUnits(length: LengthUnit.Yard)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Length(double value, LengthUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Length" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LengthUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Length, which is Meter. All conversions go via this value. + /// </summary> + public static LengthUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Length quantity. + /// </summary> + public static LengthUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Meter. + /// </summary> + public static Length Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Length AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LengthUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Length.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Angstrom"/> + /// </summary> + public double Angstroms => As(LengthUnit.Angstrom); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.AstronomicalUnit"/> + /// </summary> + public double AstronomicalUnits => As(LengthUnit.AstronomicalUnit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Centimeter"/> + /// </summary> + public double Centimeters => As(LengthUnit.Centimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Chain"/> + /// </summary> + public double Chains => As(LengthUnit.Chain); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.DataMile"/> + /// </summary> + public double DataMiles => As(LengthUnit.DataMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Decameter"/> + /// </summary> + public double Decameters => As(LengthUnit.Decameter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Decimeter"/> + /// </summary> + public double Decimeters => As(LengthUnit.Decimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.DtpPica"/> + /// </summary> + public double DtpPicas => As(LengthUnit.DtpPica); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.DtpPoint"/> + /// </summary> + public double DtpPoints => As(LengthUnit.DtpPoint); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Fathom"/> + /// </summary> + public double Fathoms => As(LengthUnit.Fathom); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Foot"/> + /// </summary> + public double Feet => As(LengthUnit.Foot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Hand"/> + /// </summary> + public double Hands => As(LengthUnit.Hand); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Hectometer"/> + /// </summary> + public double Hectometers => As(LengthUnit.Hectometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Inch"/> + /// </summary> + public double Inches => As(LengthUnit.Inch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.KilolightYear"/> + /// </summary> + public double KilolightYears => As(LengthUnit.KilolightYear); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Kilometer"/> + /// </summary> + public double Kilometers => As(LengthUnit.Kilometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Kiloparsec"/> + /// </summary> + public double Kiloparsecs => As(LengthUnit.Kiloparsec); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.LightYear"/> + /// </summary> + public double LightYears => As(LengthUnit.LightYear); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.MegalightYear"/> + /// </summary> + public double MegalightYears => As(LengthUnit.MegalightYear); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Megaparsec"/> + /// </summary> + public double Megaparsecs => As(LengthUnit.Megaparsec); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Meter"/> + /// </summary> + public double Meters => As(LengthUnit.Meter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Microinch"/> + /// </summary> + public double Microinches => As(LengthUnit.Microinch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Micrometer"/> + /// </summary> + public double Micrometers => As(LengthUnit.Micrometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Mil"/> + /// </summary> + public double Mils => As(LengthUnit.Mil); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Mile"/> + /// </summary> + public double Miles => As(LengthUnit.Mile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Millimeter"/> + /// </summary> + public double Millimeters => As(LengthUnit.Millimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Nanometer"/> + /// </summary> + public double Nanometers => As(LengthUnit.Nanometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.NauticalMile"/> + /// </summary> + public double NauticalMiles => As(LengthUnit.NauticalMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Parsec"/> + /// </summary> + public double Parsecs => As(LengthUnit.Parsec); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.PrinterPica"/> + /// </summary> + public double PrinterPicas => As(LengthUnit.PrinterPica); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.PrinterPoint"/> + /// </summary> + public double PrinterPoints => As(LengthUnit.PrinterPoint); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Shackle"/> + /// </summary> + public double Shackles => As(LengthUnit.Shackle); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.SolarRadius"/> + /// </summary> + public double SolarRadiuses => As(LengthUnit.SolarRadius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Twip"/> + /// </summary> + public double Twips => As(LengthUnit.Twip); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.UsSurveyFoot"/> + /// </summary> + public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LengthUnit.Yard"/> + /// </summary> + public double Yards => As(LengthUnit.Yard); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LengthUnit -> BaseUnit + unitConverter.SetConversionFunction<Length>(LengthUnit.Angstrom, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.AstronomicalUnit, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Centimeter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Chain, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.DataMile, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Decameter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Decimeter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.DtpPica, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.DtpPoint, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Fathom, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Foot, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Hand, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Hectometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Inch, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.KilolightYear, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Kilometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Kiloparsec, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.LightYear, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.MegalightYear, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Megaparsec, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Microinch, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Micrometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Mil, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Mile, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Millimeter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Nanometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.NauticalMile, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Parsec, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.PrinterPica, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.PrinterPoint, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Shackle, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.SolarRadius, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Twip, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.UsSurveyFoot, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Yard, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Meter, quantity => quantity); + + // Register in unit converter: BaseUnit -> LengthUnit + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Angstrom, quantity => quantity.ToUnit(LengthUnit.Angstrom)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.AstronomicalUnit, quantity => quantity.ToUnit(LengthUnit.AstronomicalUnit)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Centimeter, quantity => quantity.ToUnit(LengthUnit.Centimeter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Chain, quantity => quantity.ToUnit(LengthUnit.Chain)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.DataMile, quantity => quantity.ToUnit(LengthUnit.DataMile)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Decameter, quantity => quantity.ToUnit(LengthUnit.Decameter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Decimeter, quantity => quantity.ToUnit(LengthUnit.Decimeter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.DtpPica, quantity => quantity.ToUnit(LengthUnit.DtpPica)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.DtpPoint, quantity => quantity.ToUnit(LengthUnit.DtpPoint)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Fathom, quantity => quantity.ToUnit(LengthUnit.Fathom)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Foot, quantity => quantity.ToUnit(LengthUnit.Foot)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Hand, quantity => quantity.ToUnit(LengthUnit.Hand)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Hectometer, quantity => quantity.ToUnit(LengthUnit.Hectometer)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Inch, quantity => quantity.ToUnit(LengthUnit.Inch)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.KilolightYear, quantity => quantity.ToUnit(LengthUnit.KilolightYear)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Kilometer, quantity => quantity.ToUnit(LengthUnit.Kilometer)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Kiloparsec, quantity => quantity.ToUnit(LengthUnit.Kiloparsec)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.LightYear, quantity => quantity.ToUnit(LengthUnit.LightYear)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.MegalightYear, quantity => quantity.ToUnit(LengthUnit.MegalightYear)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Megaparsec, quantity => quantity.ToUnit(LengthUnit.Megaparsec)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Microinch, quantity => quantity.ToUnit(LengthUnit.Microinch)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Micrometer, quantity => quantity.ToUnit(LengthUnit.Micrometer)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Mil, quantity => quantity.ToUnit(LengthUnit.Mil)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Mile, quantity => quantity.ToUnit(LengthUnit.Mile)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Millimeter, quantity => quantity.ToUnit(LengthUnit.Millimeter)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Nanometer, quantity => quantity.ToUnit(LengthUnit.Nanometer)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.NauticalMile, quantity => quantity.ToUnit(LengthUnit.NauticalMile)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Parsec, quantity => quantity.ToUnit(LengthUnit.Parsec)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.PrinterPica, quantity => quantity.ToUnit(LengthUnit.PrinterPica)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.PrinterPoint, quantity => quantity.ToUnit(LengthUnit.PrinterPoint)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Shackle, quantity => quantity.ToUnit(LengthUnit.Shackle)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.SolarRadius, quantity => quantity.ToUnit(LengthUnit.SolarRadius)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Twip, quantity => quantity.ToUnit(LengthUnit.Twip)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.UsSurveyFoot, quantity => quantity.ToUnit(LengthUnit.UsSurveyFoot)); + unitConverter.SetConversionFunction<Length>(LengthUnit.Meter, LengthUnit.Yard, quantity => quantity.ToUnit(LengthUnit.Yard)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Angstrom, new CultureInfo("en-US"), false, true, new string[]{"Å", "A"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.AstronomicalUnit, new CultureInfo("en-US"), false, true, new string[]{"au", "ua"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Centimeter, new CultureInfo("en-US"), false, true, new string[]{"cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Centimeter, new CultureInfo("ru-RU"), false, true, new string[]{"см"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Centimeter, new CultureInfo("zh-CN"), false, true, new string[]{"厘米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Chain, new CultureInfo("en-US"), false, true, new string[]{"ch"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.DataMile, new CultureInfo("en-US"), false, true, new string[]{"DM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Decameter, new CultureInfo("en-US"), false, true, new string[]{"dam"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Decameter, new CultureInfo("ru-RU"), false, true, new string[]{"дам"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Decameter, new CultureInfo("zh-CN"), false, true, new string[]{"十米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Decimeter, new CultureInfo("en-US"), false, true, new string[]{"dm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Decimeter, new CultureInfo("ru-RU"), false, true, new string[]{"дм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Decimeter, new CultureInfo("zh-CN"), false, true, new string[]{"分米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.DtpPica, new CultureInfo("en-US"), false, true, new string[]{"pica"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.DtpPoint, new CultureInfo("en-US"), false, true, new string[]{"pt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Fathom, new CultureInfo("en-US"), false, true, new string[]{"fathom"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Foot, new CultureInfo("en-US"), false, true, new string[]{"ft", "'", "′"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Foot, new CultureInfo("ru-RU"), false, true, new string[]{"фут"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Foot, new CultureInfo("zh-CN"), false, true, new string[]{"英尺"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Hand, new CultureInfo("en-US"), false, true, new string[]{"h", "hh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Hectometer, new CultureInfo("en-US"), false, true, new string[]{"hm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Hectometer, new CultureInfo("ru-RU"), false, true, new string[]{"гм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Hectometer, new CultureInfo("zh-CN"), false, true, new string[]{"百米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Inch, new CultureInfo("en-US"), false, true, new string[]{"in", "\"", "″"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Inch, new CultureInfo("ru-RU"), false, true, new string[]{"дюйм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Inch, new CultureInfo("zh-CN"), false, true, new string[]{"英寸"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.KilolightYear, new CultureInfo("en-US"), false, true, new string[]{"kly"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Kilometer, new CultureInfo("en-US"), false, true, new string[]{"km"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Kilometer, new CultureInfo("ru-RU"), false, true, new string[]{"км"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Kilometer, new CultureInfo("zh-CN"), false, true, new string[]{"千米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Kiloparsec, new CultureInfo("en-US"), false, true, new string[]{"kpc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.LightYear, new CultureInfo("en-US"), false, true, new string[]{"ly"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.MegalightYear, new CultureInfo("en-US"), false, true, new string[]{"Mly"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Megaparsec, new CultureInfo("en-US"), false, true, new string[]{"Mpc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Meter, new CultureInfo("en-US"), false, true, new string[]{"m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Meter, new CultureInfo("ru-RU"), false, true, new string[]{"м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Meter, new CultureInfo("zh-CN"), false, true, new string[]{"米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Microinch, new CultureInfo("en-US"), false, true, new string[]{"µin"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Microinch, new CultureInfo("ru-RU"), false, true, new string[]{"микродюйм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Microinch, new CultureInfo("zh-CN"), false, true, new string[]{"微英寸"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Micrometer, new CultureInfo("en-US"), false, true, new string[]{"µm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Micrometer, new CultureInfo("ru-RU"), false, true, new string[]{"мкм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Micrometer, new CultureInfo("zh-CN"), false, true, new string[]{"微米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Mil, new CultureInfo("en-US"), false, true, new string[]{"mil"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Mil, new CultureInfo("ru-RU"), false, true, new string[]{"мил"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Mil, new CultureInfo("zh-CN"), false, true, new string[]{"密耳"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Mile, new CultureInfo("en-US"), false, true, new string[]{"mi"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Mile, new CultureInfo("ru-RU"), false, true, new string[]{"миля"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Mile, new CultureInfo("zh-CN"), false, true, new string[]{"英里"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Millimeter, new CultureInfo("en-US"), false, true, new string[]{"mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Millimeter, new CultureInfo("ru-RU"), false, true, new string[]{"мм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Millimeter, new CultureInfo("zh-CN"), false, true, new string[]{"毫米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Nanometer, new CultureInfo("en-US"), false, true, new string[]{"nm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Nanometer, new CultureInfo("ru-RU"), false, true, new string[]{"нм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Nanometer, new CultureInfo("zh-CN"), false, true, new string[]{"纳米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.NauticalMile, new CultureInfo("en-US"), false, true, new string[]{"NM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.NauticalMile, new CultureInfo("ru-RU"), false, true, new string[]{"мил"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.NauticalMile, new CultureInfo("zh-CN"), false, true, new string[]{"纳米"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Parsec, new CultureInfo("en-US"), false, true, new string[]{"pc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.PrinterPica, new CultureInfo("en-US"), false, true, new string[]{"pica"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.PrinterPoint, new CultureInfo("en-US"), false, true, new string[]{"pt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Shackle, new CultureInfo("en-US"), false, true, new string[]{"shackle"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.SolarRadius, new CultureInfo("en-US"), false, true, new string[]{"R⊙"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Twip, new CultureInfo("en-US"), false, true, new string[]{"twip"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.UsSurveyFoot, new CultureInfo("en-US"), false, true, new string[]{"ftUS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Yard, new CultureInfo("en-US"), false, true, new string[]{"yd"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Yard, new CultureInfo("ru-RU"), false, true, new string[]{"ярд"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LengthUnit.Yard, new CultureInfo("zh-CN"), false, true, new string[]{"码"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LengthUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Angstrom"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromAngstroms(QuantityValue angstroms) + { + double value = (double) angstroms; + return new Length(value, LengthUnit.Angstrom); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.AstronomicalUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromAstronomicalUnits(QuantityValue astronomicalunits) + { + double value = (double) astronomicalunits; + return new Length(value, LengthUnit.AstronomicalUnit); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Centimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromCentimeters(QuantityValue centimeters) + { + double value = (double) centimeters; + return new Length(value, LengthUnit.Centimeter); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Chain"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromChains(QuantityValue chains) + { + double value = (double) chains; + return new Length(value, LengthUnit.Chain); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.DataMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromDataMiles(QuantityValue datamiles) + { + double value = (double) datamiles; + return new Length(value, LengthUnit.DataMile); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Decameter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromDecameters(QuantityValue decameters) + { + double value = (double) decameters; + return new Length(value, LengthUnit.Decameter); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Decimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromDecimeters(QuantityValue decimeters) + { + double value = (double) decimeters; + return new Length(value, LengthUnit.Decimeter); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.DtpPica"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromDtpPicas(QuantityValue dtppicas) + { + double value = (double) dtppicas; + return new Length(value, LengthUnit.DtpPica); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.DtpPoint"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromDtpPoints(QuantityValue dtppoints) + { + double value = (double) dtppoints; + return new Length(value, LengthUnit.DtpPoint); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Fathom"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromFathoms(QuantityValue fathoms) + { + double value = (double) fathoms; + return new Length(value, LengthUnit.Fathom); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Foot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromFeet(QuantityValue feet) + { + double value = (double) feet; + return new Length(value, LengthUnit.Foot); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Hand"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromHands(QuantityValue hands) + { + double value = (double) hands; + return new Length(value, LengthUnit.Hand); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Hectometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromHectometers(QuantityValue hectometers) + { + double value = (double) hectometers; + return new Length(value, LengthUnit.Hectometer); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Inch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromInches(QuantityValue inches) + { + double value = (double) inches; + return new Length(value, LengthUnit.Inch); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.KilolightYear"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromKilolightYears(QuantityValue kilolightyears) + { + double value = (double) kilolightyears; + return new Length(value, LengthUnit.KilolightYear); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Kilometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromKilometers(QuantityValue kilometers) + { + double value = (double) kilometers; + return new Length(value, LengthUnit.Kilometer); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Kiloparsec"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromKiloparsecs(QuantityValue kiloparsecs) + { + double value = (double) kiloparsecs; + return new Length(value, LengthUnit.Kiloparsec); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.LightYear"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromLightYears(QuantityValue lightyears) + { + double value = (double) lightyears; + return new Length(value, LengthUnit.LightYear); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.MegalightYear"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMegalightYears(QuantityValue megalightyears) + { + double value = (double) megalightyears; + return new Length(value, LengthUnit.MegalightYear); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Megaparsec"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMegaparsecs(QuantityValue megaparsecs) + { + double value = (double) megaparsecs; + return new Length(value, LengthUnit.Megaparsec); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Meter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMeters(QuantityValue meters) + { + double value = (double) meters; + return new Length(value, LengthUnit.Meter); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Microinch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMicroinches(QuantityValue microinches) + { + double value = (double) microinches; + return new Length(value, LengthUnit.Microinch); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Micrometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMicrometers(QuantityValue micrometers) + { + double value = (double) micrometers; + return new Length(value, LengthUnit.Micrometer); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Mil"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMils(QuantityValue mils) + { + double value = (double) mils; + return new Length(value, LengthUnit.Mil); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Mile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMiles(QuantityValue miles) + { + double value = (double) miles; + return new Length(value, LengthUnit.Mile); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Millimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromMillimeters(QuantityValue millimeters) + { + double value = (double) millimeters; + return new Length(value, LengthUnit.Millimeter); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Nanometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromNanometers(QuantityValue nanometers) + { + double value = (double) nanometers; + return new Length(value, LengthUnit.Nanometer); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.NauticalMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromNauticalMiles(QuantityValue nauticalmiles) + { + double value = (double) nauticalmiles; + return new Length(value, LengthUnit.NauticalMile); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Parsec"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromParsecs(QuantityValue parsecs) + { + double value = (double) parsecs; + return new Length(value, LengthUnit.Parsec); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.PrinterPica"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromPrinterPicas(QuantityValue printerpicas) + { + double value = (double) printerpicas; + return new Length(value, LengthUnit.PrinterPica); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.PrinterPoint"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromPrinterPoints(QuantityValue printerpoints) + { + double value = (double) printerpoints; + return new Length(value, LengthUnit.PrinterPoint); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Shackle"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromShackles(QuantityValue shackles) + { + double value = (double) shackles; + return new Length(value, LengthUnit.Shackle); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.SolarRadius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromSolarRadiuses(QuantityValue solarradiuses) + { + double value = (double) solarradiuses; + return new Length(value, LengthUnit.SolarRadius); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Twip"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromTwips(QuantityValue twips) + { + double value = (double) twips; + return new Length(value, LengthUnit.Twip); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.UsSurveyFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) + { + double value = (double) ussurveyfeet; + return new Length(value, LengthUnit.UsSurveyFoot); + } + + /// <summary> + /// Creates a <see cref="Length"/> from <see cref="LengthUnit.Yard"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Length FromYards(QuantityValue yards) + { + double value = (double) yards; + return new Length(value, LengthUnit.Yard); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LengthUnit" /> to <see cref="Length" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Length unit value.</returns> + public static Length From(QuantityValue value, LengthUnit fromUnit) + { + return new Length((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Length Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Length Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Length, LengthUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Length result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Length result) + { + return QuantityParser.Default.TryParse<Length, LengthUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LengthUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LengthUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LengthUnit)"/> + public static bool TryParseUnit(string str, out LengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LengthUnit unit) + { + return UnitParser.Default.TryParse<LengthUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Length operator -(Length right) + { + return new Length(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Length"/> from adding two <see cref="Length"/>.</summary> + public static Length operator +(Length left, Length right) + { + return new Length(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Length"/> from subtracting two <see cref="Length"/>.</summary> + public static Length operator -(Length left, Length right) + { + return new Length(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Length"/> from multiplying value and <see cref="Length"/>.</summary> + public static Length operator *(double left, Length right) + { + return new Length(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Length"/> from multiplying value and <see cref="Length"/>.</summary> + public static Length operator *(Length left, double right) + { + return new Length(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Length"/> from dividing <see cref="Length"/> by value.</summary> + public static Length operator /(Length left, double right) + { + return new Length(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Length"/> by <see cref="Length"/>.</summary> + public static double operator /(Length left, Length right) + { + return left.Meters / right.Meters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Length left, Length right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Length left, Length right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Length left, Length right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Length left, Length right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Length"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Length, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Length left, Length right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Length"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Length, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Length left, Length right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Length"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Length, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Length otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Length"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Length, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Length other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Length"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Length otherQuantity)) throw new ArgumentException("Expected type Length.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Length"/> with another <see cref="Length"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Length other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Length within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Length other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Length.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LengthUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Length to another Length with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Length with the specified unit.</returns> + public Length ToUnit(LengthUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Length"/> to another <see cref="Length"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Length with the specified unit.</returns> + public Length ToUnit(LengthUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Length), Unit, typeof(Length), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Length)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Length"/> to another <see cref="Length"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Length"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LengthUnit unit, [NotNullWhen(true)] out Length? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Length? convertedOrNull = (Unit, unit) switch + { + // LengthUnit -> BaseUnit + (LengthUnit.Angstrom, LengthUnit.Meter) => new Length(_value * 1e-10, LengthUnit.Meter), + (LengthUnit.AstronomicalUnit, LengthUnit.Meter) => new Length(_value * 1.4959787070e11, LengthUnit.Meter), + (LengthUnit.Centimeter, LengthUnit.Meter) => new Length((_value) * 1e-2d, LengthUnit.Meter), + (LengthUnit.Chain, LengthUnit.Meter) => new Length(_value * 20.1168, LengthUnit.Meter), + (LengthUnit.DataMile, LengthUnit.Meter) => new Length(_value * 1828.8, LengthUnit.Meter), + (LengthUnit.Decameter, LengthUnit.Meter) => new Length((_value) * 1e1d, LengthUnit.Meter), + (LengthUnit.Decimeter, LengthUnit.Meter) => new Length((_value) * 1e-1d, LengthUnit.Meter), + (LengthUnit.DtpPica, LengthUnit.Meter) => new Length(_value / 236.220472441, LengthUnit.Meter), + (LengthUnit.DtpPoint, LengthUnit.Meter) => new Length((_value / 72) * 2.54e-2, LengthUnit.Meter), + (LengthUnit.Fathom, LengthUnit.Meter) => new Length(_value * 1.8288, LengthUnit.Meter), + (LengthUnit.Foot, LengthUnit.Meter) => new Length(_value * 0.3048, LengthUnit.Meter), + (LengthUnit.Hand, LengthUnit.Meter) => new Length(_value * 1.016e-1, LengthUnit.Meter), + (LengthUnit.Hectometer, LengthUnit.Meter) => new Length((_value) * 1e2d, LengthUnit.Meter), + (LengthUnit.Inch, LengthUnit.Meter) => new Length(_value * 2.54e-2, LengthUnit.Meter), + (LengthUnit.KilolightYear, LengthUnit.Meter) => new Length((_value * 9.46073047258e15) * 1e3d, LengthUnit.Meter), + (LengthUnit.Kilometer, LengthUnit.Meter) => new Length((_value) * 1e3d, LengthUnit.Meter), + (LengthUnit.Kiloparsec, LengthUnit.Meter) => new Length((_value * 3.08567758128e16) * 1e3d, LengthUnit.Meter), + (LengthUnit.LightYear, LengthUnit.Meter) => new Length(_value * 9.46073047258e15, LengthUnit.Meter), + (LengthUnit.MegalightYear, LengthUnit.Meter) => new Length((_value * 9.46073047258e15) * 1e6d, LengthUnit.Meter), + (LengthUnit.Megaparsec, LengthUnit.Meter) => new Length((_value * 3.08567758128e16) * 1e6d, LengthUnit.Meter), + (LengthUnit.Microinch, LengthUnit.Meter) => new Length(_value * 2.54e-8, LengthUnit.Meter), + (LengthUnit.Micrometer, LengthUnit.Meter) => new Length((_value) * 1e-6d, LengthUnit.Meter), + (LengthUnit.Mil, LengthUnit.Meter) => new Length(_value * 2.54e-5, LengthUnit.Meter), + (LengthUnit.Mile, LengthUnit.Meter) => new Length(_value * 1609.34, LengthUnit.Meter), + (LengthUnit.Millimeter, LengthUnit.Meter) => new Length((_value) * 1e-3d, LengthUnit.Meter), + (LengthUnit.Nanometer, LengthUnit.Meter) => new Length((_value) * 1e-9d, LengthUnit.Meter), + (LengthUnit.NauticalMile, LengthUnit.Meter) => new Length(_value * 1852, LengthUnit.Meter), + (LengthUnit.Parsec, LengthUnit.Meter) => new Length(_value * 3.08567758128e16, LengthUnit.Meter), + (LengthUnit.PrinterPica, LengthUnit.Meter) => new Length(_value / 237.106301584, LengthUnit.Meter), + (LengthUnit.PrinterPoint, LengthUnit.Meter) => new Length((_value / 72.27) * 2.54e-2, LengthUnit.Meter), + (LengthUnit.Shackle, LengthUnit.Meter) => new Length(_value * 27.432, LengthUnit.Meter), + (LengthUnit.SolarRadius, LengthUnit.Meter) => new Length(_value * 6.95510000E+08, LengthUnit.Meter), + (LengthUnit.Twip, LengthUnit.Meter) => new Length(_value / 56692.913385826, LengthUnit.Meter), + (LengthUnit.UsSurveyFoot, LengthUnit.Meter) => new Length(_value * 1200 / 3937, LengthUnit.Meter), + (LengthUnit.Yard, LengthUnit.Meter) => new Length(_value * 0.9144, LengthUnit.Meter), + + // BaseUnit -> LengthUnit + (LengthUnit.Meter, LengthUnit.Angstrom) => new Length(_value / 1e-10, LengthUnit.Angstrom), + (LengthUnit.Meter, LengthUnit.AstronomicalUnit) => new Length(_value / 1.4959787070e11, LengthUnit.AstronomicalUnit), + (LengthUnit.Meter, LengthUnit.Centimeter) => new Length((_value) / 1e-2d, LengthUnit.Centimeter), + (LengthUnit.Meter, LengthUnit.Chain) => new Length(_value / 20.1168, LengthUnit.Chain), + (LengthUnit.Meter, LengthUnit.DataMile) => new Length(_value / 1828.8, LengthUnit.DataMile), + (LengthUnit.Meter, LengthUnit.Decameter) => new Length((_value) / 1e1d, LengthUnit.Decameter), + (LengthUnit.Meter, LengthUnit.Decimeter) => new Length((_value) / 1e-1d, LengthUnit.Decimeter), + (LengthUnit.Meter, LengthUnit.DtpPica) => new Length(_value * 236.220472441, LengthUnit.DtpPica), + (LengthUnit.Meter, LengthUnit.DtpPoint) => new Length((_value / 2.54e-2) * 72, LengthUnit.DtpPoint), + (LengthUnit.Meter, LengthUnit.Fathom) => new Length(_value / 1.8288, LengthUnit.Fathom), + (LengthUnit.Meter, LengthUnit.Foot) => new Length(_value / 0.3048, LengthUnit.Foot), + (LengthUnit.Meter, LengthUnit.Hand) => new Length(_value / 1.016e-1, LengthUnit.Hand), + (LengthUnit.Meter, LengthUnit.Hectometer) => new Length((_value) / 1e2d, LengthUnit.Hectometer), + (LengthUnit.Meter, LengthUnit.Inch) => new Length(_value / 2.54e-2, LengthUnit.Inch), + (LengthUnit.Meter, LengthUnit.KilolightYear) => new Length((_value / 9.46073047258e15) / 1e3d, LengthUnit.KilolightYear), + (LengthUnit.Meter, LengthUnit.Kilometer) => new Length((_value) / 1e3d, LengthUnit.Kilometer), + (LengthUnit.Meter, LengthUnit.Kiloparsec) => new Length((_value / 3.08567758128e16) / 1e3d, LengthUnit.Kiloparsec), + (LengthUnit.Meter, LengthUnit.LightYear) => new Length(_value / 9.46073047258e15, LengthUnit.LightYear), + (LengthUnit.Meter, LengthUnit.MegalightYear) => new Length((_value / 9.46073047258e15) / 1e6d, LengthUnit.MegalightYear), + (LengthUnit.Meter, LengthUnit.Megaparsec) => new Length((_value / 3.08567758128e16) / 1e6d, LengthUnit.Megaparsec), + (LengthUnit.Meter, LengthUnit.Microinch) => new Length(_value / 2.54e-8, LengthUnit.Microinch), + (LengthUnit.Meter, LengthUnit.Micrometer) => new Length((_value) / 1e-6d, LengthUnit.Micrometer), + (LengthUnit.Meter, LengthUnit.Mil) => new Length(_value / 2.54e-5, LengthUnit.Mil), + (LengthUnit.Meter, LengthUnit.Mile) => new Length(_value / 1609.34, LengthUnit.Mile), + (LengthUnit.Meter, LengthUnit.Millimeter) => new Length((_value) / 1e-3d, LengthUnit.Millimeter), + (LengthUnit.Meter, LengthUnit.Nanometer) => new Length((_value) / 1e-9d, LengthUnit.Nanometer), + (LengthUnit.Meter, LengthUnit.NauticalMile) => new Length(_value / 1852, LengthUnit.NauticalMile), + (LengthUnit.Meter, LengthUnit.Parsec) => new Length(_value / 3.08567758128e16, LengthUnit.Parsec), + (LengthUnit.Meter, LengthUnit.PrinterPica) => new Length(_value * 237.106301584, LengthUnit.PrinterPica), + (LengthUnit.Meter, LengthUnit.PrinterPoint) => new Length((_value / 2.54e-2) * 72.27, LengthUnit.PrinterPoint), + (LengthUnit.Meter, LengthUnit.Shackle) => new Length(_value / 27.432, LengthUnit.Shackle), + (LengthUnit.Meter, LengthUnit.SolarRadius) => new Length(_value / 6.95510000E+08, LengthUnit.SolarRadius), + (LengthUnit.Meter, LengthUnit.Twip) => new Length(_value * 56692.913385826, LengthUnit.Twip), + (LengthUnit.Meter, LengthUnit.UsSurveyFoot) => new Length(_value * 3937 / 1200, LengthUnit.UsSurveyFoot), + (LengthUnit.Meter, LengthUnit.Yard) => new Length(_value / 0.9144, LengthUnit.Yard), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LengthUnit> IQuantity<LengthUnit>.ToUnit(LengthUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LengthUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Length)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Length)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Length)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Length)) + return this; + else if (conversionType == typeof(LengthUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Length.Info; + else if (conversionType == typeof(BaseDimensions)) + return Length.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Length)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Length/LengthUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Length/LengthUnit.g.cs new file mode 100644 index 0000000000..3c8459608b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Length/LengthUnit.g.cs @@ -0,0 +1,97 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LengthUnit + { + + /// <summary> + /// Angstrom is a metric unit of length equal to 1e-10 meter + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Angstrom</remarks> + Angstrom = 1, + + /// <summary> + /// One Astronomical Unit is the distance from the solar system Star, the sun, to planet Earth. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Astronomical_unit</remarks> + AstronomicalUnit = 2, + Centimeter = 3, + Chain = 4, + + /// <summary> + /// In radar-related subjects and in JTIDS, a data mile is a unit of distance equal to 6000 feet (1.8288 kilometres or 0.987 nautical miles). + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Data_mile</remarks> + DataMile = 5, + Decameter = 6, + Decimeter = 7, + DtpPica = 8, + DtpPoint = 9, + Fathom = 10, + Foot = 11, + Hand = 12, + Hectometer = 13, + Inch = 14, + KilolightYear = 15, + Kilometer = 16, + Kiloparsec = 17, + + /// <summary> + /// A Light Year (ly) is the distance that light travel during an Earth year, ie 365 days. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Light-year</remarks> + LightYear = 18, + MegalightYear = 19, + Megaparsec = 20, + Meter = 21, + Microinch = 22, + Micrometer = 23, + Mil = 24, + Mile = 25, + Millimeter = 26, + Nanometer = 27, + NauticalMile = 28, + + /// <summary> + /// A parsec is defined as the distance at which one astronomical unit (AU) subtends an angle of one arcsecond. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Parsec</remarks> + Parsec = 29, + PrinterPica = 30, + PrinterPoint = 31, + Shackle = 32, + + /// <summary> + /// Solar radius is a ratio unit to the radius of the solar system star, the sun. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Stellar_classification</remarks> + SolarRadius = 33, + Twip = 34, + UsSurveyFoot = 35, + Yard = 36, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Level/Level.csproj b/UnitsNet.Modular/GeneratedCode/Level/Level.csproj new file mode 100644 index 0000000000..d4eb784774 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Level/Level.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Level</Title> + <Description>Adds Level units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>level unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5c300917-a99f-d166-4f56-f0da3c3614bb}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Level</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Level/Level.g.cs b/UnitsNet.Modular/GeneratedCode/Level/Level.g.cs new file mode 100644 index 0000000000..0a27295e45 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Level/Level.g.cs @@ -0,0 +1,867 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. + /// </summary> + [DataContract] + public readonly partial struct Level : IArithmeticQuantity<Level, LevelUnit, double>, IEquatable<Level>, IComparable, IComparable<Level>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LevelUnit? _unit; + + static Level() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = LevelUnit.Decibel; + Units = Enum.GetValues(typeof(LevelUnit)).Cast<LevelUnit>().ToArray(); + Zero = new Level(0, BaseUnit); + Info = new QuantityInfo<LevelUnit>("Level", + new UnitInfo<LevelUnit>[] + { + new UnitInfo<LevelUnit>(LevelUnit.Decibel, "Decibels", BaseUnits.Undefined), + new UnitInfo<LevelUnit>(LevelUnit.Neper, "Nepers", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Level(double value, LevelUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Level" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LevelUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Level, which is Decibel. All conversions go via this value. + /// </summary> + public static LevelUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Level quantity. + /// </summary> + public static LevelUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. + /// </summary> + public static Level Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Level AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LevelUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Level.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LevelUnit.Decibel"/> + /// </summary> + public double Decibels => As(LevelUnit.Decibel); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LevelUnit.Neper"/> + /// </summary> + public double Nepers => As(LevelUnit.Neper); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LevelUnit -> BaseUnit + unitConverter.SetConversionFunction<Level>(LevelUnit.Neper, LevelUnit.Decibel, quantity => quantity.ToUnit(LevelUnit.Decibel)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Level>(LevelUnit.Decibel, LevelUnit.Decibel, quantity => quantity); + + // Register in unit converter: BaseUnit -> LevelUnit + unitConverter.SetConversionFunction<Level>(LevelUnit.Decibel, LevelUnit.Neper, quantity => quantity.ToUnit(LevelUnit.Neper)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LevelUnit.Decibel, new CultureInfo("en-US"), false, true, new string[]{"dB"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LevelUnit.Neper, new CultureInfo("en-US"), false, true, new string[]{"Np"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LevelUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LevelUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Level"/> from <see cref="LevelUnit.Decibel"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Level FromDecibels(QuantityValue decibels) + { + double value = (double) decibels; + return new Level(value, LevelUnit.Decibel); + } + + /// <summary> + /// Creates a <see cref="Level"/> from <see cref="LevelUnit.Neper"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Level FromNepers(QuantityValue nepers) + { + double value = (double) nepers; + return new Level(value, LevelUnit.Neper); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LevelUnit" /> to <see cref="Level" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Level unit value.</returns> + public static Level From(QuantityValue value, LevelUnit fromUnit) + { + return new Level((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Level Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Level Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Level, LevelUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Level result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Level result) + { + return QuantityParser.Default.TryParse<Level, LevelUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LevelUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LevelUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LevelUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LevelUnit)"/> + public static bool TryParseUnit(string str, out LevelUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LevelUnit unit) + { + return UnitParser.Default.TryParse<LevelUnit>(str, provider, out unit); + } + + #endregion + + #region Logarithmic Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Level operator -(Level right) + { + return new Level(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Level"/> from logarithmic addition of two <see cref="Level"/>.</summary> + public static Level operator +(Level left, Level right) + { + // Logarithmic addition + // Formula: 10 * log10(10^(x/10) + 10^(y/10)) + return new Level(10 * Math.Log10(Math.Pow(10, left.Value / 10) + Math.Pow(10, right.ToUnit(left.Unit).Value / 10)), left.Unit); + } + + /// <summary>Get <see cref="Level"/> from logarithmic subtraction of two <see cref="Level"/>.</summary> + public static Level operator -(Level left, Level right) + { + // Logarithmic subtraction + // Formula: 10 * log10(10^(x/10) - 10^(y/10)) + return new Level(10 * Math.Log10(Math.Pow(10, left.Value / 10) - Math.Pow(10, right.ToUnit(left.Unit).Value / 10)), left.Unit); + } + + /// <summary>Get <see cref="Level"/> from logarithmic multiplication of value and <see cref="Level"/>.</summary> + public static Level operator *(double left, Level right) + { + // Logarithmic multiplication = addition + return new Level(left + right.Value, right.Unit); + } + + /// <summary>Get <see cref="Level"/> from logarithmic multiplication of value and <see cref="Level"/>.</summary> + public static Level operator *(Level left, double right) + { + // Logarithmic multiplication = addition + return new Level(left.Value + (double)right, left.Unit); + } + + /// <summary>Get <see cref="Level"/> from logarithmic division of <see cref="Level"/> by value.</summary> + public static Level operator /(Level left, double right) + { + // Logarithmic division = subtraction + return new Level(left.Value - (double)right, left.Unit); + } + + /// <summary>Get ratio value from logarithmic division of <see cref="Level"/> by <see cref="Level"/>.</summary> + public static double operator /(Level left, Level right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Level left, Level right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Level left, Level right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Level left, Level right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Level left, Level right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Level"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Level, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Level left, Level right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Level"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Level, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Level left, Level right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Level"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Level, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Level otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Level"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Level, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Level other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Level"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Level otherQuantity)) throw new ArgumentException("Expected type Level.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Level"/> with another <see cref="Level"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Level other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Level within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Level other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Level.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LevelUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LevelUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Level to another Level with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Level with the specified unit.</returns> + public Level ToUnit(LevelUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Level"/> to another <see cref="Level"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Level with the specified unit.</returns> + public Level ToUnit(LevelUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Level), Unit, typeof(Level), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Level)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Level"/> to another <see cref="Level"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Level"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LevelUnit unit, [NotNullWhen(true)] out Level? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Level? convertedOrNull = (Unit, unit) switch + { + // LevelUnit -> BaseUnit + (LevelUnit.Neper, LevelUnit.Decibel) => new Level((1 / 0.115129254) * _value, LevelUnit.Decibel), + + // BaseUnit -> LevelUnit + (LevelUnit.Decibel, LevelUnit.Neper) => new Level(0.115129254 * _value, LevelUnit.Neper), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LevelUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LevelUnit> IQuantity<LevelUnit>.ToUnit(LevelUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LevelUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Level)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Level)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Level)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Level)) + return this; + else if (conversionType == typeof(LevelUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Level.Info; + else if (conversionType == typeof(BaseDimensions)) + return Level.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Level)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Level/LevelUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Level/LevelUnit.g.cs new file mode 100644 index 0000000000..3d1966d2b2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Level/LevelUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LevelUnit + { + Decibel = 1, + Neper = 2, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensity.csproj b/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensity.csproj new file mode 100644 index 0000000000..290072ad7f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET LinearDensity</Title> + <Description>Adds LinearDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>lineardensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{ab414094-9582-3357-d0e9-20b153a1b54c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.LinearDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensity.g.cs b/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensity.g.cs new file mode 100644 index 0000000000..6103e3d880 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensity.g.cs @@ -0,0 +1,1114 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + /// <remarks> + /// http://en.wikipedia.org/wiki/Linear_density + /// </remarks> + [DataContract] + public readonly partial struct LinearDensity : IArithmeticQuantity<LinearDensity, LinearDensityUnit, double>, IEquatable<LinearDensity>, IComparable, IComparable<LinearDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LinearDensityUnit? _unit; + + static LinearDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); + BaseUnit = LinearDensityUnit.KilogramPerMeter; + Units = Enum.GetValues(typeof(LinearDensityUnit)).Cast<LinearDensityUnit>().ToArray(); + Zero = new LinearDensity(0, BaseUnit); + Info = new QuantityInfo<LinearDensityUnit>("LinearDensity", + new UnitInfo<LinearDensityUnit>[] + { + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.GramPerCentimeter, "GramsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.GramPerMeter, "GramsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.GramPerMillimeter, "GramsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.KilogramPerCentimeter, "KilogramsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.KilogramPerMeter, "KilogramsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.KilogramPerMillimeter, "KilogramsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.MicrogramPerCentimeter, "MicrogramsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.MicrogramPerMeter, "MicrogramsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.MicrogramPerMillimeter, "MicrogramsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.MilligramPerCentimeter, "MilligramsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.MilligramPerMeter, "MilligramsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.MilligramPerMillimeter, "MilligramsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.PoundPerFoot, "PoundsPerFoot", BaseUnits.Undefined), + new UnitInfo<LinearDensityUnit>(LinearDensityUnit.PoundPerInch, "PoundsPerInch", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public LinearDensity(double value, LinearDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="LinearDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LinearDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. + /// </summary> + public static LinearDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the LinearDensity quantity. + /// </summary> + public static LinearDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. + /// </summary> + public static LinearDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static LinearDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LinearDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => LinearDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.GramPerCentimeter"/> + /// </summary> + public double GramsPerCentimeter => As(LinearDensityUnit.GramPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.GramPerMeter"/> + /// </summary> + public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.GramPerMillimeter"/> + /// </summary> + public double GramsPerMillimeter => As(LinearDensityUnit.GramPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.KilogramPerCentimeter"/> + /// </summary> + public double KilogramsPerCentimeter => As(LinearDensityUnit.KilogramPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.KilogramPerMeter"/> + /// </summary> + public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.KilogramPerMillimeter"/> + /// </summary> + public double KilogramsPerMillimeter => As(LinearDensityUnit.KilogramPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.MicrogramPerCentimeter"/> + /// </summary> + public double MicrogramsPerCentimeter => As(LinearDensityUnit.MicrogramPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.MicrogramPerMeter"/> + /// </summary> + public double MicrogramsPerMeter => As(LinearDensityUnit.MicrogramPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.MicrogramPerMillimeter"/> + /// </summary> + public double MicrogramsPerMillimeter => As(LinearDensityUnit.MicrogramPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.MilligramPerCentimeter"/> + /// </summary> + public double MilligramsPerCentimeter => As(LinearDensityUnit.MilligramPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.MilligramPerMeter"/> + /// </summary> + public double MilligramsPerMeter => As(LinearDensityUnit.MilligramPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.MilligramPerMillimeter"/> + /// </summary> + public double MilligramsPerMillimeter => As(LinearDensityUnit.MilligramPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.PoundPerFoot"/> + /// </summary> + public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearDensityUnit.PoundPerInch"/> + /// </summary> + public double PoundsPerInch => As(LinearDensityUnit.PoundPerInch); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LinearDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.GramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.GramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.GramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.MicrogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.MicrogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.MicrogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.MilligramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.MilligramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.MilligramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.PoundPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.PoundPerInch, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> LinearDensityUnit + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerCentimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerMillimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerCentimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMillimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerCentimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerMillimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerCentimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerMeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerMillimeter)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.PoundPerFoot)); + unitConverter.SetConversionFunction<LinearDensity>(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerInch, quantity => quantity.ToUnit(LinearDensityUnit.PoundPerInch)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.GramPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"g/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.GramPerMeter, new CultureInfo("en-US"), false, true, new string[]{"g/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.GramPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"g/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.KilogramPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kg/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.KilogramPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kg/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.KilogramPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kg/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.MicrogramPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"µg/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.MicrogramPerMeter, new CultureInfo("en-US"), false, true, new string[]{"µg/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.MicrogramPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"µg/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.MilligramPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mg/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.MilligramPerMeter, new CultureInfo("en-US"), false, true, new string[]{"mg/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.MilligramPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mg/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.PoundPerFoot, new CultureInfo("en-US"), false, true, new string[]{"lb/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearDensityUnit.PoundPerInch, new CultureInfo("en-US"), false, true, new string[]{"lb/in"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LinearDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LinearDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.GramPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromGramsPerCentimeter(QuantityValue gramspercentimeter) + { + double value = (double) gramspercentimeter; + return new LinearDensity(value, LinearDensityUnit.GramPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.GramPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) + { + double value = (double) gramspermeter; + return new LinearDensity(value, LinearDensityUnit.GramPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.GramPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromGramsPerMillimeter(QuantityValue gramspermillimeter) + { + double value = (double) gramspermillimeter; + return new LinearDensity(value, LinearDensityUnit.GramPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.KilogramPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromKilogramsPerCentimeter(QuantityValue kilogramspercentimeter) + { + double value = (double) kilogramspercentimeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.KilogramPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) + { + double value = (double) kilogramspermeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.KilogramPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromKilogramsPerMillimeter(QuantityValue kilogramspermillimeter) + { + double value = (double) kilogramspermillimeter; + return new LinearDensity(value, LinearDensityUnit.KilogramPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.MicrogramPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromMicrogramsPerCentimeter(QuantityValue microgramspercentimeter) + { + double value = (double) microgramspercentimeter; + return new LinearDensity(value, LinearDensityUnit.MicrogramPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.MicrogramPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromMicrogramsPerMeter(QuantityValue microgramspermeter) + { + double value = (double) microgramspermeter; + return new LinearDensity(value, LinearDensityUnit.MicrogramPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.MicrogramPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromMicrogramsPerMillimeter(QuantityValue microgramspermillimeter) + { + double value = (double) microgramspermillimeter; + return new LinearDensity(value, LinearDensityUnit.MicrogramPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.MilligramPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromMilligramsPerCentimeter(QuantityValue milligramspercentimeter) + { + double value = (double) milligramspercentimeter; + return new LinearDensity(value, LinearDensityUnit.MilligramPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.MilligramPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromMilligramsPerMeter(QuantityValue milligramspermeter) + { + double value = (double) milligramspermeter; + return new LinearDensity(value, LinearDensityUnit.MilligramPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.MilligramPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromMilligramsPerMillimeter(QuantityValue milligramspermillimeter) + { + double value = (double) milligramspermillimeter; + return new LinearDensity(value, LinearDensityUnit.MilligramPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.PoundPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) + { + double value = (double) poundsperfoot; + return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); + } + + /// <summary> + /// Creates a <see cref="LinearDensity"/> from <see cref="LinearDensityUnit.PoundPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearDensity FromPoundsPerInch(QuantityValue poundsperinch) + { + double value = (double) poundsperinch; + return new LinearDensity(value, LinearDensityUnit.PoundPerInch); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LinearDensityUnit" /> to <see cref="LinearDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>LinearDensity unit value.</returns> + public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) + { + return new LinearDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static LinearDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static LinearDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<LinearDensity, LinearDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out LinearDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out LinearDensity result) + { + return QuantityParser.Default.TryParse<LinearDensity, LinearDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LinearDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LinearDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LinearDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LinearDensityUnit)"/> + public static bool TryParseUnit(string str, out LinearDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LinearDensityUnit unit) + { + return UnitParser.Default.TryParse<LinearDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static LinearDensity operator -(LinearDensity right) + { + return new LinearDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="LinearDensity"/> from adding two <see cref="LinearDensity"/>.</summary> + public static LinearDensity operator +(LinearDensity left, LinearDensity right) + { + return new LinearDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LinearDensity"/> from subtracting two <see cref="LinearDensity"/>.</summary> + public static LinearDensity operator -(LinearDensity left, LinearDensity right) + { + return new LinearDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LinearDensity"/> from multiplying value and <see cref="LinearDensity"/>.</summary> + public static LinearDensity operator *(double left, LinearDensity right) + { + return new LinearDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="LinearDensity"/> from multiplying value and <see cref="LinearDensity"/>.</summary> + public static LinearDensity operator *(LinearDensity left, double right) + { + return new LinearDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="LinearDensity"/> from dividing <see cref="LinearDensity"/> by value.</summary> + public static LinearDensity operator /(LinearDensity left, double right) + { + return new LinearDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="LinearDensity"/> by <see cref="LinearDensity"/>.</summary> + public static double operator /(LinearDensity left, LinearDensity right) + { + return left.KilogramsPerMeter / right.KilogramsPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(LinearDensity left, LinearDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(LinearDensity left, LinearDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(LinearDensity left, LinearDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(LinearDensity left, LinearDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="LinearDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(LinearDensity left, LinearDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="LinearDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(LinearDensity left, LinearDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LinearDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is LinearDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LinearDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(LinearDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="LinearDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is LinearDensity otherQuantity)) throw new ArgumentException("Expected type LinearDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="LinearDensity"/> with another <see cref="LinearDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(LinearDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another LinearDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current LinearDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LinearDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LinearDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this LinearDensity to another LinearDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A LinearDensity with the specified unit.</returns> + public LinearDensity ToUnit(LinearDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="LinearDensity"/> to another <see cref="LinearDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A LinearDensity with the specified unit.</returns> + public LinearDensity ToUnit(LinearDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(LinearDensity), Unit, typeof(LinearDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (LinearDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="LinearDensity"/> to another <see cref="LinearDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="LinearDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LinearDensityUnit unit, [NotNullWhen(true)] out LinearDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + LinearDensity? convertedOrNull = (Unit, unit) switch + { + // LinearDensityUnit -> BaseUnit + (LinearDensityUnit.GramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 1e-1, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.GramPerMeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 1e-3, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.GramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.KilogramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-1) * 1e3d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.KilogramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value) * 1e3d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.MicrogramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-1) * 1e-6d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.MicrogramPerMeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-3) * 1e-6d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.MicrogramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value) * 1e-6d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.MilligramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-1) * 1e-3d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.MilligramPerMeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-3) * 1e-3d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.MilligramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value) * 1e-3d, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.PoundPerFoot, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 1.48816394, LinearDensityUnit.KilogramPerMeter), + (LinearDensityUnit.PoundPerInch, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value / 5.5997415e-2, LinearDensityUnit.KilogramPerMeter), + + // BaseUnit -> LinearDensityUnit + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerCentimeter) => new LinearDensity(_value / 1e-1, LinearDensityUnit.GramPerCentimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMeter) => new LinearDensity(_value / 1e-3, LinearDensityUnit.GramPerMeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMillimeter) => new LinearDensity(_value, LinearDensityUnit.GramPerMillimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerCentimeter) => new LinearDensity((_value / 1e-1) / 1e3d, LinearDensityUnit.KilogramPerCentimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMillimeter) => new LinearDensity((_value) / 1e3d, LinearDensityUnit.KilogramPerMillimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerCentimeter) => new LinearDensity((_value / 1e-1) / 1e-6d, LinearDensityUnit.MicrogramPerCentimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMeter) => new LinearDensity((_value / 1e-3) / 1e-6d, LinearDensityUnit.MicrogramPerMeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMillimeter) => new LinearDensity((_value) / 1e-6d, LinearDensityUnit.MicrogramPerMillimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerCentimeter) => new LinearDensity((_value / 1e-1) / 1e-3d, LinearDensityUnit.MilligramPerCentimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMeter) => new LinearDensity((_value / 1e-3) / 1e-3d, LinearDensityUnit.MilligramPerMeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMillimeter) => new LinearDensity((_value) / 1e-3d, LinearDensityUnit.MilligramPerMillimeter), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerFoot) => new LinearDensity(_value / 1.48816394, LinearDensityUnit.PoundPerFoot), + (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerInch) => new LinearDensity(_value * 5.5997415e-2, LinearDensityUnit.PoundPerInch), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LinearDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LinearDensityUnit> IQuantity<LinearDensityUnit>.ToUnit(LinearDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LinearDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LinearDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LinearDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LinearDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(LinearDensity)) + return this; + else if (conversionType == typeof(LinearDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return LinearDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return LinearDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(LinearDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensityUnit.g.cs new file mode 100644 index 0000000000..652bf6b524 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LinearDensity/LinearDensityUnit.g.cs @@ -0,0 +1,45 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LinearDensityUnit + { + GramPerCentimeter = 1, + GramPerMeter = 2, + GramPerMillimeter = 3, + KilogramPerCentimeter = 4, + KilogramPerMeter = 5, + KilogramPerMillimeter = 6, + MicrogramPerCentimeter = 7, + MicrogramPerMeter = 8, + MicrogramPerMillimeter = 9, + MilligramPerCentimeter = 10, + MilligramPerMeter = 11, + MilligramPerMillimeter = 12, + PoundPerFoot = 13, + PoundPerInch = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensity.csproj b/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensity.csproj new file mode 100644 index 0000000000..d0ed13c6ad --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET LinearPowerDensity</Title> + <Description>Adds LinearPowerDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>linearpowerdensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8823a9ee-673a-e7d4-3c0a-bae61a262388}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.LinearPowerDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensity.g.cs b/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensity.g.cs new file mode 100644 index 0000000000..6c1e6ca60c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensity.g.cs @@ -0,0 +1,1345 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The Linear Power Density of a substance is its power 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. + /// </summary> + /// <remarks> + /// http://en.wikipedia.org/wiki/Linear_density + /// </remarks> + [DataContract] + public readonly partial struct LinearPowerDensity : IArithmeticQuantity<LinearPowerDensity, LinearPowerDensityUnit, double>, IEquatable<LinearPowerDensity>, IComparable, IComparable<LinearPowerDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LinearPowerDensityUnit? _unit; + + static LinearPowerDensity() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); + BaseUnit = LinearPowerDensityUnit.WattPerMeter; + Units = Enum.GetValues(typeof(LinearPowerDensityUnit)).Cast<LinearPowerDensityUnit>().ToArray(); + Zero = new LinearPowerDensity(0, BaseUnit); + Info = new QuantityInfo<LinearPowerDensityUnit>("LinearPowerDensity", + new UnitInfo<LinearPowerDensityUnit>[] + { + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.GigawattPerCentimeter, "GigawattsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.GigawattPerFoot, "GigawattsPerFoot", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.GigawattPerInch, "GigawattsPerInch", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.GigawattPerMeter, "GigawattsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.GigawattPerMillimeter, "GigawattsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.KilowattPerCentimeter, "KilowattsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.KilowattPerFoot, "KilowattsPerFoot", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.KilowattPerInch, "KilowattsPerInch", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.KilowattPerMeter, "KilowattsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.KilowattPerMillimeter, "KilowattsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MegawattPerCentimeter, "MegawattsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MegawattPerFoot, "MegawattsPerFoot", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MegawattPerInch, "MegawattsPerInch", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MegawattPerMeter, "MegawattsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MegawattPerMillimeter, "MegawattsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MilliwattPerCentimeter, "MilliwattsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MilliwattPerFoot, "MilliwattsPerFoot", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MilliwattPerInch, "MilliwattsPerInch", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MilliwattPerMeter, "MilliwattsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.MilliwattPerMillimeter, "MilliwattsPerMillimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.WattPerCentimeter, "WattsPerCentimeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.WattPerFoot, "WattsPerFoot", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.WattPerInch, "WattsPerInch", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.WattPerMeter, "WattsPerMeter", BaseUnits.Undefined), + new UnitInfo<LinearPowerDensityUnit>(LinearPowerDensityUnit.WattPerMillimeter, "WattsPerMillimeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public LinearPowerDensity(double value, LinearPowerDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="LinearPowerDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LinearPowerDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of LinearPowerDensity, which is WattPerMeter. All conversions go via this value. + /// </summary> + public static LinearPowerDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the LinearPowerDensity quantity. + /// </summary> + public static LinearPowerDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeter. + /// </summary> + public static LinearPowerDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static LinearPowerDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LinearPowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LinearPowerDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => LinearPowerDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.GigawattPerCentimeter"/> + /// </summary> + public double GigawattsPerCentimeter => As(LinearPowerDensityUnit.GigawattPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.GigawattPerFoot"/> + /// </summary> + public double GigawattsPerFoot => As(LinearPowerDensityUnit.GigawattPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.GigawattPerInch"/> + /// </summary> + public double GigawattsPerInch => As(LinearPowerDensityUnit.GigawattPerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.GigawattPerMeter"/> + /// </summary> + public double GigawattsPerMeter => As(LinearPowerDensityUnit.GigawattPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.GigawattPerMillimeter"/> + /// </summary> + public double GigawattsPerMillimeter => As(LinearPowerDensityUnit.GigawattPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.KilowattPerCentimeter"/> + /// </summary> + public double KilowattsPerCentimeter => As(LinearPowerDensityUnit.KilowattPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.KilowattPerFoot"/> + /// </summary> + public double KilowattsPerFoot => As(LinearPowerDensityUnit.KilowattPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.KilowattPerInch"/> + /// </summary> + public double KilowattsPerInch => As(LinearPowerDensityUnit.KilowattPerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.KilowattPerMeter"/> + /// </summary> + public double KilowattsPerMeter => As(LinearPowerDensityUnit.KilowattPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.KilowattPerMillimeter"/> + /// </summary> + public double KilowattsPerMillimeter => As(LinearPowerDensityUnit.KilowattPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MegawattPerCentimeter"/> + /// </summary> + public double MegawattsPerCentimeter => As(LinearPowerDensityUnit.MegawattPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MegawattPerFoot"/> + /// </summary> + public double MegawattsPerFoot => As(LinearPowerDensityUnit.MegawattPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MegawattPerInch"/> + /// </summary> + public double MegawattsPerInch => As(LinearPowerDensityUnit.MegawattPerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MegawattPerMeter"/> + /// </summary> + public double MegawattsPerMeter => As(LinearPowerDensityUnit.MegawattPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MegawattPerMillimeter"/> + /// </summary> + public double MegawattsPerMillimeter => As(LinearPowerDensityUnit.MegawattPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MilliwattPerCentimeter"/> + /// </summary> + public double MilliwattsPerCentimeter => As(LinearPowerDensityUnit.MilliwattPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MilliwattPerFoot"/> + /// </summary> + public double MilliwattsPerFoot => As(LinearPowerDensityUnit.MilliwattPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MilliwattPerInch"/> + /// </summary> + public double MilliwattsPerInch => As(LinearPowerDensityUnit.MilliwattPerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MilliwattPerMeter"/> + /// </summary> + public double MilliwattsPerMeter => As(LinearPowerDensityUnit.MilliwattPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.MilliwattPerMillimeter"/> + /// </summary> + public double MilliwattsPerMillimeter => As(LinearPowerDensityUnit.MilliwattPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.WattPerCentimeter"/> + /// </summary> + public double WattsPerCentimeter => As(LinearPowerDensityUnit.WattPerCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.WattPerFoot"/> + /// </summary> + public double WattsPerFoot => As(LinearPowerDensityUnit.WattPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.WattPerInch"/> + /// </summary> + public double WattsPerInch => As(LinearPowerDensityUnit.WattPerInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.WattPerMeter"/> + /// </summary> + public double WattsPerMeter => As(LinearPowerDensityUnit.WattPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LinearPowerDensityUnit.WattPerMillimeter"/> + /// </summary> + public double WattsPerMillimeter => As(LinearPowerDensityUnit.WattPerMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LinearPowerDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.GigawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.GigawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.GigawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.GigawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.GigawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.KilowattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.KilowattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.KilowattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.KilowattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.KilowattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MegawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MegawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MegawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MegawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MegawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MilliwattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MilliwattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MilliwattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MilliwattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.MilliwattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> LinearPowerDensityUnit + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerCentimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerFoot)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerInch)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerMillimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerCentimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerFoot)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerInch)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerMillimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerCentimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerFoot)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerInch)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerMillimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerCentimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerFoot)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerInch)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerMeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerMillimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerCentimeter)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerFoot)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerInch)); + unitConverter.SetConversionFunction<LinearPowerDensity>(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.GigawattPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"GW/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.GigawattPerFoot, new CultureInfo("en-US"), false, true, new string[]{"GW/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.GigawattPerInch, new CultureInfo("en-US"), false, true, new string[]{"GW/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.GigawattPerMeter, new CultureInfo("en-US"), false, true, new string[]{"GW/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.GigawattPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"GW/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.KilowattPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kW/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.KilowattPerFoot, new CultureInfo("en-US"), false, true, new string[]{"kW/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.KilowattPerInch, new CultureInfo("en-US"), false, true, new string[]{"kW/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.KilowattPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kW/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.KilowattPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kW/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MegawattPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"MW/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MegawattPerFoot, new CultureInfo("en-US"), false, true, new string[]{"MW/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MegawattPerInch, new CultureInfo("en-US"), false, true, new string[]{"MW/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MegawattPerMeter, new CultureInfo("en-US"), false, true, new string[]{"MW/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MegawattPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"MW/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MilliwattPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mW/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MilliwattPerFoot, new CultureInfo("en-US"), false, true, new string[]{"mW/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MilliwattPerInch, new CultureInfo("en-US"), false, true, new string[]{"mW/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MilliwattPerMeter, new CultureInfo("en-US"), false, true, new string[]{"mW/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.MilliwattPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mW/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.WattPerCentimeter, new CultureInfo("en-US"), false, true, new string[]{"W/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.WattPerFoot, new CultureInfo("en-US"), false, true, new string[]{"W/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.WattPerInch, new CultureInfo("en-US"), false, true, new string[]{"W/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.WattPerMeter, new CultureInfo("en-US"), false, true, new string[]{"W/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LinearPowerDensityUnit.WattPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"W/mm"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LinearPowerDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LinearPowerDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.GigawattPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromGigawattsPerCentimeter(QuantityValue gigawattspercentimeter) + { + double value = (double) gigawattspercentimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.GigawattPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromGigawattsPerFoot(QuantityValue gigawattsperfoot) + { + double value = (double) gigawattsperfoot; + return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerFoot); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.GigawattPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromGigawattsPerInch(QuantityValue gigawattsperinch) + { + double value = (double) gigawattsperinch; + return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerInch); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.GigawattPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromGigawattsPerMeter(QuantityValue gigawattspermeter) + { + double value = (double) gigawattspermeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.GigawattPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromGigawattsPerMillimeter(QuantityValue gigawattspermillimeter) + { + double value = (double) gigawattspermillimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.KilowattPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromKilowattsPerCentimeter(QuantityValue kilowattspercentimeter) + { + double value = (double) kilowattspercentimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.KilowattPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromKilowattsPerFoot(QuantityValue kilowattsperfoot) + { + double value = (double) kilowattsperfoot; + return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerFoot); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.KilowattPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromKilowattsPerInch(QuantityValue kilowattsperinch) + { + double value = (double) kilowattsperinch; + return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerInch); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.KilowattPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromKilowattsPerMeter(QuantityValue kilowattspermeter) + { + double value = (double) kilowattspermeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.KilowattPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromKilowattsPerMillimeter(QuantityValue kilowattspermillimeter) + { + double value = (double) kilowattspermillimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MegawattPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMegawattsPerCentimeter(QuantityValue megawattspercentimeter) + { + double value = (double) megawattspercentimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MegawattPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMegawattsPerFoot(QuantityValue megawattsperfoot) + { + double value = (double) megawattsperfoot; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerFoot); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MegawattPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMegawattsPerInch(QuantityValue megawattsperinch) + { + double value = (double) megawattsperinch; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerInch); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MegawattPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMegawattsPerMeter(QuantityValue megawattspermeter) + { + double value = (double) megawattspermeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MegawattPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMegawattsPerMillimeter(QuantityValue megawattspermillimeter) + { + double value = (double) megawattspermillimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MilliwattPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMilliwattsPerCentimeter(QuantityValue milliwattspercentimeter) + { + double value = (double) milliwattspercentimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MilliwattPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMilliwattsPerFoot(QuantityValue milliwattsperfoot) + { + double value = (double) milliwattsperfoot; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerFoot); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MilliwattPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMilliwattsPerInch(QuantityValue milliwattsperinch) + { + double value = (double) milliwattsperinch; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerInch); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MilliwattPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMilliwattsPerMeter(QuantityValue milliwattspermeter) + { + double value = (double) milliwattspermeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.MilliwattPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromMilliwattsPerMillimeter(QuantityValue milliwattspermillimeter) + { + double value = (double) milliwattspermillimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.WattPerCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromWattsPerCentimeter(QuantityValue wattspercentimeter) + { + double value = (double) wattspercentimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerCentimeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.WattPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromWattsPerFoot(QuantityValue wattsperfoot) + { + double value = (double) wattsperfoot; + return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerFoot); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.WattPerInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromWattsPerInch(QuantityValue wattsperinch) + { + double value = (double) wattsperinch; + return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerInch); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.WattPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromWattsPerMeter(QuantityValue wattspermeter) + { + double value = (double) wattspermeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMeter); + } + + /// <summary> + /// Creates a <see cref="LinearPowerDensity"/> from <see cref="LinearPowerDensityUnit.WattPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LinearPowerDensity FromWattsPerMillimeter(QuantityValue wattspermillimeter) + { + double value = (double) wattspermillimeter; + return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LinearPowerDensityUnit" /> to <see cref="LinearPowerDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>LinearPowerDensity unit value.</returns> + public static LinearPowerDensity From(QuantityValue value, LinearPowerDensityUnit fromUnit) + { + return new LinearPowerDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static LinearPowerDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static LinearPowerDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<LinearPowerDensity, LinearPowerDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out LinearPowerDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out LinearPowerDensity result) + { + return QuantityParser.Default.TryParse<LinearPowerDensity, LinearPowerDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LinearPowerDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LinearPowerDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LinearPowerDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LinearPowerDensityUnit)"/> + public static bool TryParseUnit(string str, out LinearPowerDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LinearPowerDensityUnit unit) + { + return UnitParser.Default.TryParse<LinearPowerDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static LinearPowerDensity operator -(LinearPowerDensity right) + { + return new LinearPowerDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="LinearPowerDensity"/> from adding two <see cref="LinearPowerDensity"/>.</summary> + public static LinearPowerDensity operator +(LinearPowerDensity left, LinearPowerDensity right) + { + return new LinearPowerDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LinearPowerDensity"/> from subtracting two <see cref="LinearPowerDensity"/>.</summary> + public static LinearPowerDensity operator -(LinearPowerDensity left, LinearPowerDensity right) + { + return new LinearPowerDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LinearPowerDensity"/> from multiplying value and <see cref="LinearPowerDensity"/>.</summary> + public static LinearPowerDensity operator *(double left, LinearPowerDensity right) + { + return new LinearPowerDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="LinearPowerDensity"/> from multiplying value and <see cref="LinearPowerDensity"/>.</summary> + public static LinearPowerDensity operator *(LinearPowerDensity left, double right) + { + return new LinearPowerDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="LinearPowerDensity"/> from dividing <see cref="LinearPowerDensity"/> by value.</summary> + public static LinearPowerDensity operator /(LinearPowerDensity left, double right) + { + return new LinearPowerDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="LinearPowerDensity"/> by <see cref="LinearPowerDensity"/>.</summary> + public static double operator /(LinearPowerDensity left, LinearPowerDensity right) + { + return left.WattsPerMeter / right.WattsPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(LinearPowerDensity left, LinearPowerDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(LinearPowerDensity left, LinearPowerDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(LinearPowerDensity left, LinearPowerDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(LinearPowerDensity left, LinearPowerDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="LinearPowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearPowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(LinearPowerDensity left, LinearPowerDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="LinearPowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearPowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(LinearPowerDensity left, LinearPowerDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LinearPowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearPowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is LinearPowerDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LinearPowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LinearPowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(LinearPowerDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="LinearPowerDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is LinearPowerDensity otherQuantity)) throw new ArgumentException("Expected type LinearPowerDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="LinearPowerDensity"/> with another <see cref="LinearPowerDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(LinearPowerDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another LinearPowerDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(LinearPowerDensity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current LinearPowerDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LinearPowerDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LinearPowerDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this LinearPowerDensity to another LinearPowerDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A LinearPowerDensity with the specified unit.</returns> + public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="LinearPowerDensity"/> to another <see cref="LinearPowerDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A LinearPowerDensity with the specified unit.</returns> + public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(LinearPowerDensity), Unit, typeof(LinearPowerDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (LinearPowerDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="LinearPowerDensity"/> to another <see cref="LinearPowerDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="LinearPowerDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LinearPowerDensityUnit unit, [NotNullWhen(true)] out LinearPowerDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + LinearPowerDensity? convertedOrNull = (Unit, unit) switch + { + // LinearPowerDensityUnit -> BaseUnit + (LinearPowerDensityUnit.GigawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e9d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.GigawattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 3.280839895) * 1e9d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.GigawattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 39.37007874) * 1e9d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.GigawattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e9d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.GigawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e9d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.KilowattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.KilowattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 3.280839895) * 1e3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.KilowattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 39.37007874) * 1e3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.KilowattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.KilowattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MegawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e6d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MegawattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 3.280839895) * 1e6d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MegawattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 39.37007874) * 1e6d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MegawattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e6d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MegawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e6d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MilliwattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MilliwattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 3.280839895) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MilliwattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 39.37007874) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MilliwattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.MilliwattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.WattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value * 1e2, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.WattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value * 3.280839895, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.WattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value * 39.37007874, LinearPowerDensityUnit.WattPerMeter), + (LinearPowerDensityUnit.WattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value * 1e3, LinearPowerDensityUnit.WattPerMeter), + + // BaseUnit -> LinearPowerDensityUnit + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e9d, LinearPowerDensityUnit.GigawattPerCentimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerFoot) => new LinearPowerDensity((_value / 3.280839895) / 1e9d, LinearPowerDensityUnit.GigawattPerFoot), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerInch) => new LinearPowerDensity((_value / 39.37007874) / 1e9d, LinearPowerDensityUnit.GigawattPerInch), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMeter) => new LinearPowerDensity((_value) / 1e9d, LinearPowerDensityUnit.GigawattPerMeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e9d, LinearPowerDensityUnit.GigawattPerMillimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e3d, LinearPowerDensityUnit.KilowattPerCentimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerFoot) => new LinearPowerDensity((_value / 3.280839895) / 1e3d, LinearPowerDensityUnit.KilowattPerFoot), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerInch) => new LinearPowerDensity((_value / 39.37007874) / 1e3d, LinearPowerDensityUnit.KilowattPerInch), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMeter) => new LinearPowerDensity((_value) / 1e3d, LinearPowerDensityUnit.KilowattPerMeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e3d, LinearPowerDensityUnit.KilowattPerMillimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e6d, LinearPowerDensityUnit.MegawattPerCentimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerFoot) => new LinearPowerDensity((_value / 3.280839895) / 1e6d, LinearPowerDensityUnit.MegawattPerFoot), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerInch) => new LinearPowerDensity((_value / 39.37007874) / 1e6d, LinearPowerDensityUnit.MegawattPerInch), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMeter) => new LinearPowerDensity((_value) / 1e6d, LinearPowerDensityUnit.MegawattPerMeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e6d, LinearPowerDensityUnit.MegawattPerMillimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e-3d, LinearPowerDensityUnit.MilliwattPerCentimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerFoot) => new LinearPowerDensity((_value / 3.280839895) / 1e-3d, LinearPowerDensityUnit.MilliwattPerFoot), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerInch) => new LinearPowerDensity((_value / 39.37007874) / 1e-3d, LinearPowerDensityUnit.MilliwattPerInch), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMeter) => new LinearPowerDensity((_value) / 1e-3d, LinearPowerDensityUnit.MilliwattPerMeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e-3d, LinearPowerDensityUnit.MilliwattPerMillimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerCentimeter) => new LinearPowerDensity(_value / 1e2, LinearPowerDensityUnit.WattPerCentimeter), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerFoot) => new LinearPowerDensity(_value / 3.280839895, LinearPowerDensityUnit.WattPerFoot), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerInch) => new LinearPowerDensity(_value / 39.37007874, LinearPowerDensityUnit.WattPerInch), + (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMillimeter) => new LinearPowerDensity(_value / 1e3, LinearPowerDensityUnit.WattPerMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LinearPowerDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LinearPowerDensityUnit> IQuantity<LinearPowerDensityUnit>.ToUnit(LinearPowerDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LinearPowerDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(LinearPowerDensity)) + return this; + else if (conversionType == typeof(LinearPowerDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return LinearPowerDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return LinearPowerDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensityUnit.g.cs new file mode 100644 index 0000000000..2ab6e250ac --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LinearPowerDensity/LinearPowerDensityUnit.g.cs @@ -0,0 +1,56 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LinearPowerDensityUnit + { + GigawattPerCentimeter = 1, + GigawattPerFoot = 2, + GigawattPerInch = 3, + GigawattPerMeter = 4, + GigawattPerMillimeter = 5, + KilowattPerCentimeter = 6, + KilowattPerFoot = 7, + KilowattPerInch = 8, + KilowattPerMeter = 9, + KilowattPerMillimeter = 10, + MegawattPerCentimeter = 11, + MegawattPerFoot = 12, + MegawattPerInch = 13, + MegawattPerMeter = 14, + MegawattPerMillimeter = 15, + MilliwattPerCentimeter = 16, + MilliwattPerFoot = 17, + MilliwattPerInch = 18, + MilliwattPerMeter = 19, + MilliwattPerMillimeter = 20, + WattPerCentimeter = 21, + WattPerFoot = 22, + WattPerInch = 23, + WattPerMeter = 24, + WattPerMillimeter = 25, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Luminance/Luminance.csproj b/UnitsNet.Modular/GeneratedCode/Luminance/Luminance.csproj new file mode 100644 index 0000000000..3146a959ab --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Luminance/Luminance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Luminance</Title> + <Description>Adds Luminance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>luminance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{cbded274-6b9b-a113-d56f-00b38006cc84}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Luminance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Luminance/Luminance.g.cs b/UnitsNet.Modular/GeneratedCode/Luminance/Luminance.g.cs new file mode 100644 index 0000000000..4c1bcff794 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Luminance/Luminance.g.cs @@ -0,0 +1,1030 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Luminance + /// </remarks> + [DataContract] + public readonly partial struct Luminance : IArithmeticQuantity<Luminance, LuminanceUnit, double>, IEquatable<Luminance>, IComparable, IComparable<Luminance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LuminanceUnit? _unit; + + static Luminance() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + BaseUnit = LuminanceUnit.CandelaPerSquareMeter; + Units = Enum.GetValues(typeof(LuminanceUnit)).Cast<LuminanceUnit>().ToArray(); + Zero = new Luminance(0, BaseUnit); + Info = new QuantityInfo<LuminanceUnit>("Luminance", + new UnitInfo<LuminanceUnit>[] + { + new UnitInfo<LuminanceUnit>(LuminanceUnit.CandelaPerSquareFoot, "CandelasPerSquareFoot", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.CandelaPerSquareInch, "CandelasPerSquareInch", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.CandelaPerSquareMeter, "CandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, luminousIntensity: LuminousIntensityUnit.Candela)), + new UnitInfo<LuminanceUnit>(LuminanceUnit.CenticandelaPerSquareMeter, "CenticandelasPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.DecicandelaPerSquareMeter, "DecicandelasPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.KilocandelaPerSquareMeter, "KilocandelasPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.MicrocandelaPerSquareMeter, "MicrocandelasPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.MillicandelaPerSquareMeter, "MillicandelasPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.NanocandelaPerSquareMeter, "NanocandelasPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<LuminanceUnit>(LuminanceUnit.Nit, "Nits", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Luminance(double value, LuminanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Luminance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LuminanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Luminance, which is CandelaPerSquareMeter. All conversions go via this value. + /// </summary> + public static LuminanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Luminance quantity. + /// </summary> + public static LuminanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CandelaPerSquareMeter. + /// </summary> + public static Luminance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Luminance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LuminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LuminanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Luminance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.CandelaPerSquareFoot"/> + /// </summary> + public double CandelasPerSquareFoot => As(LuminanceUnit.CandelaPerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.CandelaPerSquareInch"/> + /// </summary> + public double CandelasPerSquareInch => As(LuminanceUnit.CandelaPerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.CandelaPerSquareMeter"/> + /// </summary> + public double CandelasPerSquareMeter => As(LuminanceUnit.CandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.CenticandelaPerSquareMeter"/> + /// </summary> + public double CenticandelasPerSquareMeter => As(LuminanceUnit.CenticandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.DecicandelaPerSquareMeter"/> + /// </summary> + public double DecicandelasPerSquareMeter => As(LuminanceUnit.DecicandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.KilocandelaPerSquareMeter"/> + /// </summary> + public double KilocandelasPerSquareMeter => As(LuminanceUnit.KilocandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.MicrocandelaPerSquareMeter"/> + /// </summary> + public double MicrocandelasPerSquareMeter => As(LuminanceUnit.MicrocandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.MillicandelaPerSquareMeter"/> + /// </summary> + public double MillicandelasPerSquareMeter => As(LuminanceUnit.MillicandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.NanocandelaPerSquareMeter"/> + /// </summary> + public double NanocandelasPerSquareMeter => As(LuminanceUnit.NanocandelaPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminanceUnit.Nit"/> + /// </summary> + public double Nits => As(LuminanceUnit.Nit); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LuminanceUnit -> BaseUnit + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareFoot, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareInch, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CenticandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.DecicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.KilocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.MicrocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.MillicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.NanocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.Nit, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> LuminanceUnit + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareFoot, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareFoot)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareInch, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareInch)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CenticandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CenticandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.DecicandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.DecicandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.KilocandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.KilocandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MicrocandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.MicrocandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MillicandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.MillicandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.NanocandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.NanocandelaPerSquareMeter)); + unitConverter.SetConversionFunction<Luminance>(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.Nit, quantity => quantity.ToUnit(LuminanceUnit.Nit)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.CandelaPerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"Cd/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.CandelaPerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"Cd/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.CandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"Cd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.CenticandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"cCd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.DecicandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"dCd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.KilocandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kCd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.MicrocandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"µCd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.MillicandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"mCd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.NanocandelaPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"nCd/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminanceUnit.Nit, new CultureInfo("en-US"), false, true, new string[]{"nt"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LuminanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LuminanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.CandelaPerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromCandelasPerSquareFoot(QuantityValue candelaspersquarefoot) + { + double value = (double) candelaspersquarefoot; + return new Luminance(value, LuminanceUnit.CandelaPerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.CandelaPerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromCandelasPerSquareInch(QuantityValue candelaspersquareinch) + { + double value = (double) candelaspersquareinch; + return new Luminance(value, LuminanceUnit.CandelaPerSquareInch); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.CandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromCandelasPerSquareMeter(QuantityValue candelaspersquaremeter) + { + double value = (double) candelaspersquaremeter; + return new Luminance(value, LuminanceUnit.CandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.CenticandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromCenticandelasPerSquareMeter(QuantityValue centicandelaspersquaremeter) + { + double value = (double) centicandelaspersquaremeter; + return new Luminance(value, LuminanceUnit.CenticandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.DecicandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromDecicandelasPerSquareMeter(QuantityValue decicandelaspersquaremeter) + { + double value = (double) decicandelaspersquaremeter; + return new Luminance(value, LuminanceUnit.DecicandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.KilocandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromKilocandelasPerSquareMeter(QuantityValue kilocandelaspersquaremeter) + { + double value = (double) kilocandelaspersquaremeter; + return new Luminance(value, LuminanceUnit.KilocandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.MicrocandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromMicrocandelasPerSquareMeter(QuantityValue microcandelaspersquaremeter) + { + double value = (double) microcandelaspersquaremeter; + return new Luminance(value, LuminanceUnit.MicrocandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.MillicandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromMillicandelasPerSquareMeter(QuantityValue millicandelaspersquaremeter) + { + double value = (double) millicandelaspersquaremeter; + return new Luminance(value, LuminanceUnit.MillicandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.NanocandelaPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromNanocandelasPerSquareMeter(QuantityValue nanocandelaspersquaremeter) + { + double value = (double) nanocandelaspersquaremeter; + return new Luminance(value, LuminanceUnit.NanocandelaPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Luminance"/> from <see cref="LuminanceUnit.Nit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminance FromNits(QuantityValue nits) + { + double value = (double) nits; + return new Luminance(value, LuminanceUnit.Nit); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LuminanceUnit" /> to <see cref="Luminance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Luminance unit value.</returns> + public static Luminance From(QuantityValue value, LuminanceUnit fromUnit) + { + return new Luminance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Luminance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Luminance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Luminance, LuminanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Luminance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Luminance result) + { + return QuantityParser.Default.TryParse<Luminance, LuminanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LuminanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LuminanceUnit)"/> + public static bool TryParseUnit(string str, out LuminanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminanceUnit unit) + { + return UnitParser.Default.TryParse<LuminanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Luminance operator -(Luminance right) + { + return new Luminance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Luminance"/> from adding two <see cref="Luminance"/>.</summary> + public static Luminance operator +(Luminance left, Luminance right) + { + return new Luminance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Luminance"/> from subtracting two <see cref="Luminance"/>.</summary> + public static Luminance operator -(Luminance left, Luminance right) + { + return new Luminance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Luminance"/> from multiplying value and <see cref="Luminance"/>.</summary> + public static Luminance operator *(double left, Luminance right) + { + return new Luminance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Luminance"/> from multiplying value and <see cref="Luminance"/>.</summary> + public static Luminance operator *(Luminance left, double right) + { + return new Luminance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Luminance"/> from dividing <see cref="Luminance"/> by value.</summary> + public static Luminance operator /(Luminance left, double right) + { + return new Luminance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Luminance"/> by <see cref="Luminance"/>.</summary> + public static double operator /(Luminance left, Luminance right) + { + return left.CandelasPerSquareMeter / right.CandelasPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Luminance left, Luminance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Luminance left, Luminance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Luminance left, Luminance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Luminance left, Luminance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Luminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Luminance left, Luminance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Luminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Luminance left, Luminance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Luminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Luminance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Luminance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Luminance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Luminance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Luminance otherQuantity)) throw new ArgumentException("Expected type Luminance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Luminance"/> with another <see cref="Luminance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Luminance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Luminance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Luminance other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Luminance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LuminanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LuminanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Luminance to another Luminance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Luminance with the specified unit.</returns> + public Luminance ToUnit(LuminanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Luminance"/> to another <see cref="Luminance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Luminance with the specified unit.</returns> + public Luminance ToUnit(LuminanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Luminance), Unit, typeof(Luminance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Luminance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Luminance"/> to another <see cref="Luminance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Luminance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LuminanceUnit unit, [NotNullWhen(true)] out Luminance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Luminance? convertedOrNull = (Unit, unit) switch + { + // LuminanceUnit -> BaseUnit + (LuminanceUnit.CandelaPerSquareFoot, LuminanceUnit.CandelaPerSquareMeter) => new Luminance(_value* 1.07639e1, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareInch, LuminanceUnit.CandelaPerSquareMeter) => new Luminance(_value* 1.5500031e3, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.CenticandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-2d, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.DecicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-1d, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.KilocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e3d, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.MicrocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-6d, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.MillicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-3d, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.NanocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-9d, LuminanceUnit.CandelaPerSquareMeter), + (LuminanceUnit.Nit, LuminanceUnit.CandelaPerSquareMeter) => new Luminance(_value, LuminanceUnit.CandelaPerSquareMeter), + + // BaseUnit -> LuminanceUnit + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareFoot) => new Luminance(_value/ 1.07639e1, LuminanceUnit.CandelaPerSquareFoot), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareInch) => new Luminance(_value/ 1.5500031e3, LuminanceUnit.CandelaPerSquareInch), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CenticandelaPerSquareMeter) => new Luminance((_value) / 1e-2d, LuminanceUnit.CenticandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.DecicandelaPerSquareMeter) => new Luminance((_value) / 1e-1d, LuminanceUnit.DecicandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.KilocandelaPerSquareMeter) => new Luminance((_value) / 1e3d, LuminanceUnit.KilocandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MicrocandelaPerSquareMeter) => new Luminance((_value) / 1e-6d, LuminanceUnit.MicrocandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MillicandelaPerSquareMeter) => new Luminance((_value) / 1e-3d, LuminanceUnit.MillicandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.NanocandelaPerSquareMeter) => new Luminance((_value) / 1e-9d, LuminanceUnit.NanocandelaPerSquareMeter), + (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.Nit) => new Luminance(_value, LuminanceUnit.Nit), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LuminanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LuminanceUnit> IQuantity<LuminanceUnit>.ToUnit(LuminanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LuminanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Luminance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Luminance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Luminance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Luminance)) + return this; + else if (conversionType == typeof(LuminanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Luminance.Info; + else if (conversionType == typeof(BaseDimensions)) + return Luminance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Luminance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Luminance/LuminanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Luminance/LuminanceUnit.g.cs new file mode 100644 index 0000000000..24814e4dcc --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Luminance/LuminanceUnit.g.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LuminanceUnit + { + CandelaPerSquareFoot = 10, + CandelaPerSquareInch = 7, + CandelaPerSquareMeter = 8, + CenticandelaPerSquareMeter = 3, + DecicandelaPerSquareMeter = 4, + KilocandelaPerSquareMeter = 9, + MicrocandelaPerSquareMeter = 6, + MillicandelaPerSquareMeter = 2, + NanocandelaPerSquareMeter = 1, + /// <remarks>https://www.britannica.com/science/luminosity</remarks> + Nit = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Luminosity/Luminosity.csproj b/UnitsNet.Modular/GeneratedCode/Luminosity/Luminosity.csproj new file mode 100644 index 0000000000..0c8e8413ec --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Luminosity/Luminosity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Luminosity</Title> + <Description>Adds Luminosity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>luminosity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{fe30ed04-094f-5005-b0aa-1b3623db60b2}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Luminosity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Luminosity/Luminosity.g.cs b/UnitsNet.Modular/GeneratedCode/Luminosity/Luminosity.g.cs new file mode 100644 index 0000000000..2fb343a179 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Luminosity/Luminosity.g.cs @@ -0,0 +1,1114 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Luminosity + /// </remarks> + [DataContract] + public readonly partial struct Luminosity : IArithmeticQuantity<Luminosity, LuminosityUnit, double>, IEquatable<Luminosity>, IComparable, IComparable<Luminosity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LuminosityUnit? _unit; + + static Luminosity() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + BaseUnit = LuminosityUnit.Watt; + Units = Enum.GetValues(typeof(LuminosityUnit)).Cast<LuminosityUnit>().ToArray(); + Zero = new Luminosity(0, BaseUnit); + Info = new QuantityInfo<LuminosityUnit>("Luminosity", + new UnitInfo<LuminosityUnit>[] + { + new UnitInfo<LuminosityUnit>(LuminosityUnit.Decawatt, "Decawatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Deciwatt, "Deciwatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Femtowatt, "Femtowatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Gigawatt, "Gigawatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Kilowatt, "Kilowatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Megawatt, "Megawatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Microwatt, "Microwatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Milliwatt, "Milliwatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Nanowatt, "Nanowatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Petawatt, "Petawatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Picowatt, "Picowatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.SolarLuminosity, "SolarLuminosities", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Terawatt, "Terawatts", BaseUnits.Undefined), + new UnitInfo<LuminosityUnit>(LuminosityUnit.Watt, "Watts", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Luminosity(double value, LuminosityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Luminosity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LuminosityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Luminosity, which is Watt. All conversions go via this value. + /// </summary> + public static LuminosityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Luminosity quantity. + /// </summary> + public static LuminosityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Watt. + /// </summary> + public static Luminosity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Luminosity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LuminosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LuminosityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Luminosity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Decawatt"/> + /// </summary> + public double Decawatts => As(LuminosityUnit.Decawatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Deciwatt"/> + /// </summary> + public double Deciwatts => As(LuminosityUnit.Deciwatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Femtowatt"/> + /// </summary> + public double Femtowatts => As(LuminosityUnit.Femtowatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Gigawatt"/> + /// </summary> + public double Gigawatts => As(LuminosityUnit.Gigawatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Kilowatt"/> + /// </summary> + public double Kilowatts => As(LuminosityUnit.Kilowatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Megawatt"/> + /// </summary> + public double Megawatts => As(LuminosityUnit.Megawatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Microwatt"/> + /// </summary> + public double Microwatts => As(LuminosityUnit.Microwatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Milliwatt"/> + /// </summary> + public double Milliwatts => As(LuminosityUnit.Milliwatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Nanowatt"/> + /// </summary> + public double Nanowatts => As(LuminosityUnit.Nanowatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Petawatt"/> + /// </summary> + public double Petawatts => As(LuminosityUnit.Petawatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Picowatt"/> + /// </summary> + public double Picowatts => As(LuminosityUnit.Picowatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.SolarLuminosity"/> + /// </summary> + public double SolarLuminosities => As(LuminosityUnit.SolarLuminosity); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Terawatt"/> + /// </summary> + public double Terawatts => As(LuminosityUnit.Terawatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminosityUnit.Watt"/> + /// </summary> + public double Watts => As(LuminosityUnit.Watt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LuminosityUnit -> BaseUnit + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Decawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Deciwatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Femtowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Gigawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Kilowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Megawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Microwatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Milliwatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Nanowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Petawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Picowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.SolarLuminosity, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Terawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Watt, quantity => quantity); + + // Register in unit converter: BaseUnit -> LuminosityUnit + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Decawatt, quantity => quantity.ToUnit(LuminosityUnit.Decawatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Deciwatt, quantity => quantity.ToUnit(LuminosityUnit.Deciwatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Femtowatt, quantity => quantity.ToUnit(LuminosityUnit.Femtowatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Gigawatt, quantity => quantity.ToUnit(LuminosityUnit.Gigawatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Kilowatt, quantity => quantity.ToUnit(LuminosityUnit.Kilowatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Megawatt, quantity => quantity.ToUnit(LuminosityUnit.Megawatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Microwatt, quantity => quantity.ToUnit(LuminosityUnit.Microwatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Milliwatt, quantity => quantity.ToUnit(LuminosityUnit.Milliwatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Nanowatt, quantity => quantity.ToUnit(LuminosityUnit.Nanowatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Petawatt, quantity => quantity.ToUnit(LuminosityUnit.Petawatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Picowatt, quantity => quantity.ToUnit(LuminosityUnit.Picowatt)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.SolarLuminosity, quantity => quantity.ToUnit(LuminosityUnit.SolarLuminosity)); + unitConverter.SetConversionFunction<Luminosity>(LuminosityUnit.Watt, LuminosityUnit.Terawatt, quantity => quantity.ToUnit(LuminosityUnit.Terawatt)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Decawatt, new CultureInfo("en-US"), false, true, new string[]{"daW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Deciwatt, new CultureInfo("en-US"), false, true, new string[]{"dW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Femtowatt, new CultureInfo("en-US"), false, true, new string[]{"fW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Gigawatt, new CultureInfo("en-US"), false, true, new string[]{"GW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Kilowatt, new CultureInfo("en-US"), false, true, new string[]{"kW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Megawatt, new CultureInfo("en-US"), false, true, new string[]{"MW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Microwatt, new CultureInfo("en-US"), false, true, new string[]{"µW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Milliwatt, new CultureInfo("en-US"), false, true, new string[]{"mW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Nanowatt, new CultureInfo("en-US"), false, true, new string[]{"nW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Petawatt, new CultureInfo("en-US"), false, true, new string[]{"PW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Picowatt, new CultureInfo("en-US"), false, true, new string[]{"pW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.SolarLuminosity, new CultureInfo("en-US"), false, true, new string[]{"L⊙"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Terawatt, new CultureInfo("en-US"), false, true, new string[]{"TW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(LuminosityUnit.Watt, new CultureInfo("en-US"), false, true, new string[]{"W"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LuminosityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LuminosityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Decawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromDecawatts(QuantityValue decawatts) + { + double value = (double) decawatts; + return new Luminosity(value, LuminosityUnit.Decawatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Deciwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromDeciwatts(QuantityValue deciwatts) + { + double value = (double) deciwatts; + return new Luminosity(value, LuminosityUnit.Deciwatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Femtowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromFemtowatts(QuantityValue femtowatts) + { + double value = (double) femtowatts; + return new Luminosity(value, LuminosityUnit.Femtowatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Gigawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromGigawatts(QuantityValue gigawatts) + { + double value = (double) gigawatts; + return new Luminosity(value, LuminosityUnit.Gigawatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Kilowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromKilowatts(QuantityValue kilowatts) + { + double value = (double) kilowatts; + return new Luminosity(value, LuminosityUnit.Kilowatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Megawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromMegawatts(QuantityValue megawatts) + { + double value = (double) megawatts; + return new Luminosity(value, LuminosityUnit.Megawatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Microwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromMicrowatts(QuantityValue microwatts) + { + double value = (double) microwatts; + return new Luminosity(value, LuminosityUnit.Microwatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Milliwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromMilliwatts(QuantityValue milliwatts) + { + double value = (double) milliwatts; + return new Luminosity(value, LuminosityUnit.Milliwatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Nanowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromNanowatts(QuantityValue nanowatts) + { + double value = (double) nanowatts; + return new Luminosity(value, LuminosityUnit.Nanowatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Petawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromPetawatts(QuantityValue petawatts) + { + double value = (double) petawatts; + return new Luminosity(value, LuminosityUnit.Petawatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Picowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromPicowatts(QuantityValue picowatts) + { + double value = (double) picowatts; + return new Luminosity(value, LuminosityUnit.Picowatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.SolarLuminosity"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromSolarLuminosities(QuantityValue solarluminosities) + { + double value = (double) solarluminosities; + return new Luminosity(value, LuminosityUnit.SolarLuminosity); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Terawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromTerawatts(QuantityValue terawatts) + { + double value = (double) terawatts; + return new Luminosity(value, LuminosityUnit.Terawatt); + } + + /// <summary> + /// Creates a <see cref="Luminosity"/> from <see cref="LuminosityUnit.Watt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Luminosity FromWatts(QuantityValue watts) + { + double value = (double) watts; + return new Luminosity(value, LuminosityUnit.Watt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LuminosityUnit" /> to <see cref="Luminosity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Luminosity unit value.</returns> + public static Luminosity From(QuantityValue value, LuminosityUnit fromUnit) + { + return new Luminosity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Luminosity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Luminosity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Luminosity, LuminosityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Luminosity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Luminosity result) + { + return QuantityParser.Default.TryParse<Luminosity, LuminosityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminosityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminosityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LuminosityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LuminosityUnit)"/> + public static bool TryParseUnit(string str, out LuminosityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminosityUnit unit) + { + return UnitParser.Default.TryParse<LuminosityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Luminosity operator -(Luminosity right) + { + return new Luminosity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Luminosity"/> from adding two <see cref="Luminosity"/>.</summary> + public static Luminosity operator +(Luminosity left, Luminosity right) + { + return new Luminosity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Luminosity"/> from subtracting two <see cref="Luminosity"/>.</summary> + public static Luminosity operator -(Luminosity left, Luminosity right) + { + return new Luminosity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Luminosity"/> from multiplying value and <see cref="Luminosity"/>.</summary> + public static Luminosity operator *(double left, Luminosity right) + { + return new Luminosity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Luminosity"/> from multiplying value and <see cref="Luminosity"/>.</summary> + public static Luminosity operator *(Luminosity left, double right) + { + return new Luminosity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Luminosity"/> from dividing <see cref="Luminosity"/> by value.</summary> + public static Luminosity operator /(Luminosity left, double right) + { + return new Luminosity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Luminosity"/> by <see cref="Luminosity"/>.</summary> + public static double operator /(Luminosity left, Luminosity right) + { + return left.Watts / right.Watts; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Luminosity left, Luminosity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Luminosity left, Luminosity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Luminosity left, Luminosity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Luminosity left, Luminosity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Luminosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Luminosity left, Luminosity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Luminosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Luminosity left, Luminosity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Luminosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Luminosity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Luminosity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Luminosity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Luminosity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Luminosity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Luminosity otherQuantity)) throw new ArgumentException("Expected type Luminosity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Luminosity"/> with another <see cref="Luminosity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Luminosity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Luminosity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Luminosity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Luminosity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LuminosityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LuminosityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Luminosity to another Luminosity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Luminosity with the specified unit.</returns> + public Luminosity ToUnit(LuminosityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Luminosity"/> to another <see cref="Luminosity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Luminosity with the specified unit.</returns> + public Luminosity ToUnit(LuminosityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Luminosity), Unit, typeof(Luminosity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Luminosity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Luminosity"/> to another <see cref="Luminosity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Luminosity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LuminosityUnit unit, [NotNullWhen(true)] out Luminosity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Luminosity? convertedOrNull = (Unit, unit) switch + { + // LuminosityUnit -> BaseUnit + (LuminosityUnit.Decawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e1d, LuminosityUnit.Watt), + (LuminosityUnit.Deciwatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-1d, LuminosityUnit.Watt), + (LuminosityUnit.Femtowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-15d, LuminosityUnit.Watt), + (LuminosityUnit.Gigawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e9d, LuminosityUnit.Watt), + (LuminosityUnit.Kilowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e3d, LuminosityUnit.Watt), + (LuminosityUnit.Megawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e6d, LuminosityUnit.Watt), + (LuminosityUnit.Microwatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-6d, LuminosityUnit.Watt), + (LuminosityUnit.Milliwatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-3d, LuminosityUnit.Watt), + (LuminosityUnit.Nanowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-9d, LuminosityUnit.Watt), + (LuminosityUnit.Petawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e15d, LuminosityUnit.Watt), + (LuminosityUnit.Picowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-12d, LuminosityUnit.Watt), + (LuminosityUnit.SolarLuminosity, LuminosityUnit.Watt) => new Luminosity(_value * 3.846e26, LuminosityUnit.Watt), + (LuminosityUnit.Terawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e12d, LuminosityUnit.Watt), + + // BaseUnit -> LuminosityUnit + (LuminosityUnit.Watt, LuminosityUnit.Decawatt) => new Luminosity((_value) / 1e1d, LuminosityUnit.Decawatt), + (LuminosityUnit.Watt, LuminosityUnit.Deciwatt) => new Luminosity((_value) / 1e-1d, LuminosityUnit.Deciwatt), + (LuminosityUnit.Watt, LuminosityUnit.Femtowatt) => new Luminosity((_value) / 1e-15d, LuminosityUnit.Femtowatt), + (LuminosityUnit.Watt, LuminosityUnit.Gigawatt) => new Luminosity((_value) / 1e9d, LuminosityUnit.Gigawatt), + (LuminosityUnit.Watt, LuminosityUnit.Kilowatt) => new Luminosity((_value) / 1e3d, LuminosityUnit.Kilowatt), + (LuminosityUnit.Watt, LuminosityUnit.Megawatt) => new Luminosity((_value) / 1e6d, LuminosityUnit.Megawatt), + (LuminosityUnit.Watt, LuminosityUnit.Microwatt) => new Luminosity((_value) / 1e-6d, LuminosityUnit.Microwatt), + (LuminosityUnit.Watt, LuminosityUnit.Milliwatt) => new Luminosity((_value) / 1e-3d, LuminosityUnit.Milliwatt), + (LuminosityUnit.Watt, LuminosityUnit.Nanowatt) => new Luminosity((_value) / 1e-9d, LuminosityUnit.Nanowatt), + (LuminosityUnit.Watt, LuminosityUnit.Petawatt) => new Luminosity((_value) / 1e15d, LuminosityUnit.Petawatt), + (LuminosityUnit.Watt, LuminosityUnit.Picowatt) => new Luminosity((_value) / 1e-12d, LuminosityUnit.Picowatt), + (LuminosityUnit.Watt, LuminosityUnit.SolarLuminosity) => new Luminosity(_value / 3.846e26, LuminosityUnit.SolarLuminosity), + (LuminosityUnit.Watt, LuminosityUnit.Terawatt) => new Luminosity((_value) / 1e12d, LuminosityUnit.Terawatt), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LuminosityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LuminosityUnit> IQuantity<LuminosityUnit>.ToUnit(LuminosityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LuminosityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Luminosity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Luminosity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Luminosity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Luminosity)) + return this; + else if (conversionType == typeof(LuminosityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Luminosity.Info; + else if (conversionType == typeof(BaseDimensions)) + return Luminosity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Luminosity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Luminosity/LuminosityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Luminosity/LuminosityUnit.g.cs new file mode 100644 index 0000000000..44cdfec58c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Luminosity/LuminosityUnit.g.cs @@ -0,0 +1,46 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LuminosityUnit + { + Decawatt = 1, + Deciwatt = 2, + Femtowatt = 3, + Gigawatt = 4, + Kilowatt = 5, + Megawatt = 6, + Microwatt = 7, + Milliwatt = 8, + Nanowatt = 9, + Petawatt = 10, + Picowatt = 11, + /// <remarks>https://www.britannica.com/science/luminosity</remarks> + SolarLuminosity = 12, + Terawatt = 13, + Watt = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFlux.csproj b/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFlux.csproj new file mode 100644 index 0000000000..51d47b100b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFlux.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET LuminousFlux</Title> + <Description>Adds LuminousFlux units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>luminousflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{a38e4da2-f05f-aa6f-82f1-56cd2e062d96}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.LuminousFlux</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFlux.g.cs b/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFlux.g.cs new file mode 100644 index 0000000000..0ca8578bf3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFlux.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In photometry, luminous flux or luminous power is the measure of the perceived power of light. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Luminous_flux + /// </remarks> + [DataContract] + public readonly partial struct LuminousFlux : IArithmeticQuantity<LuminousFlux, LuminousFluxUnit, double>, IEquatable<LuminousFlux>, IComparable, IComparable<LuminousFlux>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LuminousFluxUnit? _unit; + + static LuminousFlux() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + BaseUnit = LuminousFluxUnit.Lumen; + Units = Enum.GetValues(typeof(LuminousFluxUnit)).Cast<LuminousFluxUnit>().ToArray(); + Zero = new LuminousFlux(0, BaseUnit); + Info = new QuantityInfo<LuminousFluxUnit>("LuminousFlux", + new UnitInfo<LuminousFluxUnit>[] + { + new UnitInfo<LuminousFluxUnit>(LuminousFluxUnit.Lumen, "Lumens", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public LuminousFlux(double value, LuminousFluxUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="LuminousFlux" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LuminousFluxUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. + /// </summary> + public static LuminousFluxUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the LuminousFlux quantity. + /// </summary> + public static LuminousFluxUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. + /// </summary> + public static LuminousFlux Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static LuminousFlux AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LuminousFluxUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminousFluxUnit.Lumen"/> + /// </summary> + public double Lumens => As(LuminousFluxUnit.Lumen); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LuminousFluxUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<LuminousFlux>(LuminousFluxUnit.Lumen, LuminousFluxUnit.Lumen, quantity => quantity); + + // Register in unit converter: BaseUnit -> LuminousFluxUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LuminousFluxUnit.Lumen, new CultureInfo("en-US"), false, true, new string[]{"lm"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LuminousFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LuminousFluxUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="LuminousFlux"/> from <see cref="LuminousFluxUnit.Lumen"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LuminousFlux FromLumens(QuantityValue lumens) + { + double value = (double) lumens; + return new LuminousFlux(value, LuminousFluxUnit.Lumen); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LuminousFluxUnit" /> to <see cref="LuminousFlux" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>LuminousFlux unit value.</returns> + public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) + { + return new LuminousFlux((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static LuminousFlux Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static LuminousFlux Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<LuminousFlux, LuminousFluxUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out LuminousFlux result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out LuminousFlux result) + { + return QuantityParser.Default.TryParse<LuminousFlux, LuminousFluxUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminousFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminousFluxUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LuminousFluxUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LuminousFluxUnit)"/> + public static bool TryParseUnit(string str, out LuminousFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminousFluxUnit unit) + { + return UnitParser.Default.TryParse<LuminousFluxUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static LuminousFlux operator -(LuminousFlux right) + { + return new LuminousFlux(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="LuminousFlux"/> from adding two <see cref="LuminousFlux"/>.</summary> + public static LuminousFlux operator +(LuminousFlux left, LuminousFlux right) + { + return new LuminousFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LuminousFlux"/> from subtracting two <see cref="LuminousFlux"/>.</summary> + public static LuminousFlux operator -(LuminousFlux left, LuminousFlux right) + { + return new LuminousFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LuminousFlux"/> from multiplying value and <see cref="LuminousFlux"/>.</summary> + public static LuminousFlux operator *(double left, LuminousFlux right) + { + return new LuminousFlux(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="LuminousFlux"/> from multiplying value and <see cref="LuminousFlux"/>.</summary> + public static LuminousFlux operator *(LuminousFlux left, double right) + { + return new LuminousFlux(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="LuminousFlux"/> from dividing <see cref="LuminousFlux"/> by value.</summary> + public static LuminousFlux operator /(LuminousFlux left, double right) + { + return new LuminousFlux(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="LuminousFlux"/> by <see cref="LuminousFlux"/>.</summary> + public static double operator /(LuminousFlux left, LuminousFlux right) + { + return left.Lumens / right.Lumens; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(LuminousFlux left, LuminousFlux right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(LuminousFlux left, LuminousFlux right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(LuminousFlux left, LuminousFlux right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(LuminousFlux left, LuminousFlux right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="LuminousFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(LuminousFlux left, LuminousFlux right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="LuminousFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(LuminousFlux left, LuminousFlux right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LuminousFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is LuminousFlux otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LuminousFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(LuminousFlux other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="LuminousFlux"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is LuminousFlux otherQuantity)) throw new ArgumentException("Expected type LuminousFlux.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="LuminousFlux"/> with another <see cref="LuminousFlux"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(LuminousFlux other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another LuminousFlux within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current LuminousFlux.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LuminousFluxUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LuminousFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this LuminousFlux to another LuminousFlux with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A LuminousFlux with the specified unit.</returns> + public LuminousFlux ToUnit(LuminousFluxUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="LuminousFlux"/> to another <see cref="LuminousFlux"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A LuminousFlux with the specified unit.</returns> + public LuminousFlux ToUnit(LuminousFluxUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(LuminousFlux), Unit, typeof(LuminousFlux), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (LuminousFlux)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="LuminousFlux"/> to another <see cref="LuminousFlux"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="LuminousFlux"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LuminousFluxUnit unit, [NotNullWhen(true)] out LuminousFlux? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + LuminousFlux? convertedOrNull = (Unit, unit) switch + { + // LuminousFluxUnit -> BaseUnit + + // BaseUnit -> LuminousFluxUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LuminousFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LuminousFluxUnit> IQuantity<LuminousFluxUnit>.ToUnit(LuminousFluxUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LuminousFluxUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(LuminousFlux)) + return this; + else if (conversionType == typeof(LuminousFluxUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return LuminousFlux.Info; + else if (conversionType == typeof(BaseDimensions)) + return LuminousFlux.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFluxUnit.g.cs b/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFluxUnit.g.cs new file mode 100644 index 0000000000..01a956a02c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LuminousFlux/LuminousFluxUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LuminousFluxUnit + { + Lumen = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensity.csproj b/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensity.csproj new file mode 100644 index 0000000000..ec973142ed --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET LuminousIntensity</Title> + <Description>Adds LuminousIntensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>luminousintensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{733f9598-101b-936b-b081-2805dd793091}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.LuminousIntensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensity.g.cs b/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensity.g.cs new file mode 100644 index 0000000000..4b356f4ab2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensity.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Luminous_intensity + /// </remarks> + [DataContract] + public readonly partial struct LuminousIntensity : IArithmeticQuantity<LuminousIntensity, LuminousIntensityUnit, double>, IEquatable<LuminousIntensity>, IComparable, IComparable<LuminousIntensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly LuminousIntensityUnit? _unit; + + static LuminousIntensity() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + BaseUnit = LuminousIntensityUnit.Candela; + Units = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast<LuminousIntensityUnit>().ToArray(); + Zero = new LuminousIntensity(0, BaseUnit); + Info = new QuantityInfo<LuminousIntensityUnit>("LuminousIntensity", + new UnitInfo<LuminousIntensityUnit>[] + { + new UnitInfo<LuminousIntensityUnit>(LuminousIntensityUnit.Candela, "Candela", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public LuminousIntensity(double value, LuminousIntensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="LuminousIntensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<LuminousIntensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. + /// </summary> + public static LuminousIntensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the LuminousIntensity quantity. + /// </summary> + public static LuminousIntensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Candela. + /// </summary> + public static LuminousIntensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static LuminousIntensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<LuminousIntensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="LuminousIntensityUnit.Candela"/> + /// </summary> + public double Candela => As(LuminousIntensityUnit.Candela); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: LuminousIntensityUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<LuminousIntensity>(LuminousIntensityUnit.Candela, LuminousIntensityUnit.Candela, quantity => quantity); + + // Register in unit converter: BaseUnit -> LuminousIntensityUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(LuminousIntensityUnit.Candela, new CultureInfo("en-US"), false, true, new string[]{"cd"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(LuminousIntensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(LuminousIntensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="LuminousIntensity"/> from <see cref="LuminousIntensityUnit.Candela"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static LuminousIntensity FromCandela(QuantityValue candela) + { + double value = (double) candela; + return new LuminousIntensity(value, LuminousIntensityUnit.Candela); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="LuminousIntensityUnit" /> to <see cref="LuminousIntensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>LuminousIntensity unit value.</returns> + public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) + { + return new LuminousIntensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static LuminousIntensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static LuminousIntensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<LuminousIntensity, LuminousIntensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out LuminousIntensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out LuminousIntensity result) + { + return QuantityParser.Default.TryParse<LuminousIntensity, LuminousIntensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminousIntensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static LuminousIntensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<LuminousIntensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.LuminousIntensityUnit)"/> + public static bool TryParseUnit(string str, out LuminousIntensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out LuminousIntensityUnit unit) + { + return UnitParser.Default.TryParse<LuminousIntensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static LuminousIntensity operator -(LuminousIntensity right) + { + return new LuminousIntensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="LuminousIntensity"/> from adding two <see cref="LuminousIntensity"/>.</summary> + public static LuminousIntensity operator +(LuminousIntensity left, LuminousIntensity right) + { + return new LuminousIntensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LuminousIntensity"/> from subtracting two <see cref="LuminousIntensity"/>.</summary> + public static LuminousIntensity operator -(LuminousIntensity left, LuminousIntensity right) + { + return new LuminousIntensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="LuminousIntensity"/> from multiplying value and <see cref="LuminousIntensity"/>.</summary> + public static LuminousIntensity operator *(double left, LuminousIntensity right) + { + return new LuminousIntensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="LuminousIntensity"/> from multiplying value and <see cref="LuminousIntensity"/>.</summary> + public static LuminousIntensity operator *(LuminousIntensity left, double right) + { + return new LuminousIntensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="LuminousIntensity"/> from dividing <see cref="LuminousIntensity"/> by value.</summary> + public static LuminousIntensity operator /(LuminousIntensity left, double right) + { + return new LuminousIntensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="LuminousIntensity"/> by <see cref="LuminousIntensity"/>.</summary> + public static double operator /(LuminousIntensity left, LuminousIntensity right) + { + return left.Candela / right.Candela; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(LuminousIntensity left, LuminousIntensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(LuminousIntensity left, LuminousIntensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(LuminousIntensity left, LuminousIntensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(LuminousIntensity left, LuminousIntensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="LuminousIntensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousIntensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(LuminousIntensity left, LuminousIntensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="LuminousIntensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousIntensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(LuminousIntensity left, LuminousIntensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LuminousIntensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousIntensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is LuminousIntensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="LuminousIntensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(LuminousIntensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(LuminousIntensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="LuminousIntensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is LuminousIntensity otherQuantity)) throw new ArgumentException("Expected type LuminousIntensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="LuminousIntensity"/> with another <see cref="LuminousIntensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(LuminousIntensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another LuminousIntensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current LuminousIntensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(LuminousIntensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is LuminousIntensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A LuminousIntensity with the specified unit.</returns> + public LuminousIntensity ToUnit(LuminousIntensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="LuminousIntensity"/> to another <see cref="LuminousIntensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A LuminousIntensity with the specified unit.</returns> + public LuminousIntensity ToUnit(LuminousIntensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(LuminousIntensity), Unit, typeof(LuminousIntensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (LuminousIntensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="LuminousIntensity"/> to another <see cref="LuminousIntensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="LuminousIntensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(LuminousIntensityUnit unit, [NotNullWhen(true)] out LuminousIntensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + LuminousIntensity? convertedOrNull = (Unit, unit) switch + { + // LuminousIntensityUnit -> BaseUnit + + // BaseUnit -> LuminousIntensityUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is LuminousIntensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<LuminousIntensityUnit> IQuantity<LuminousIntensityUnit>.ToUnit(LuminousIntensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<LuminousIntensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(LuminousIntensity)) + return this; + else if (conversionType == typeof(LuminousIntensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return LuminousIntensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return LuminousIntensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensityUnit.g.cs new file mode 100644 index 0000000000..947d36fb22 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/LuminousIntensity/LuminousIntensityUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum LuminousIntensityUnit + { + Candela = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticField.csproj b/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticField.csproj new file mode 100644 index 0000000000..1a02841c91 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticField.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MagneticField</Title> + <Description>Adds MagneticField units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>magneticfield unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{809c4afa-d014-471b-518b-4fd01cb7c808}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MagneticField</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticField.g.cs b/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticField.g.cs new file mode 100644 index 0000000000..d90d8724f1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticField.g.cs @@ -0,0 +1,946 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Magnetic_field + /// </remarks> + [DataContract] + public readonly partial struct MagneticField : IArithmeticQuantity<MagneticField, MagneticFieldUnit, double>, IEquatable<MagneticField>, IComparable, IComparable<MagneticField>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MagneticFieldUnit? _unit; + + static MagneticField() + { + BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); + BaseUnit = MagneticFieldUnit.Tesla; + Units = Enum.GetValues(typeof(MagneticFieldUnit)).Cast<MagneticFieldUnit>().ToArray(); + Zero = new MagneticField(0, BaseUnit); + Info = new QuantityInfo<MagneticFieldUnit>("MagneticField", + new UnitInfo<MagneticFieldUnit>[] + { + new UnitInfo<MagneticFieldUnit>(MagneticFieldUnit.Gauss, "Gausses", BaseUnits.Undefined), + new UnitInfo<MagneticFieldUnit>(MagneticFieldUnit.Microtesla, "Microteslas", BaseUnits.Undefined), + new UnitInfo<MagneticFieldUnit>(MagneticFieldUnit.Milligauss, "Milligausses", BaseUnits.Undefined), + new UnitInfo<MagneticFieldUnit>(MagneticFieldUnit.Millitesla, "Milliteslas", BaseUnits.Undefined), + new UnitInfo<MagneticFieldUnit>(MagneticFieldUnit.Nanotesla, "Nanoteslas", BaseUnits.Undefined), + new UnitInfo<MagneticFieldUnit>(MagneticFieldUnit.Tesla, "Teslas", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MagneticField(double value, MagneticFieldUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MagneticField" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MagneticFieldUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MagneticField, which is Tesla. All conversions go via this value. + /// </summary> + public static MagneticFieldUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MagneticField quantity. + /// </summary> + public static MagneticFieldUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. + /// </summary> + public static MagneticField Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MagneticField AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MagneticFieldUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MagneticField.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFieldUnit.Gauss"/> + /// </summary> + public double Gausses => As(MagneticFieldUnit.Gauss); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFieldUnit.Microtesla"/> + /// </summary> + public double Microteslas => As(MagneticFieldUnit.Microtesla); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFieldUnit.Milligauss"/> + /// </summary> + public double Milligausses => As(MagneticFieldUnit.Milligauss); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFieldUnit.Millitesla"/> + /// </summary> + public double Milliteslas => As(MagneticFieldUnit.Millitesla); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFieldUnit.Nanotesla"/> + /// </summary> + public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFieldUnit.Tesla"/> + /// </summary> + public double Teslas => As(MagneticFieldUnit.Tesla); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MagneticFieldUnit -> BaseUnit + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Gauss, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Microtesla, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Milligauss, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Millitesla, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Nanotesla, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Tesla, MagneticFieldUnit.Tesla, quantity => quantity); + + // Register in unit converter: BaseUnit -> MagneticFieldUnit + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Tesla, MagneticFieldUnit.Gauss, quantity => quantity.ToUnit(MagneticFieldUnit.Gauss)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Tesla, MagneticFieldUnit.Microtesla, quantity => quantity.ToUnit(MagneticFieldUnit.Microtesla)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Tesla, MagneticFieldUnit.Milligauss, quantity => quantity.ToUnit(MagneticFieldUnit.Milligauss)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Tesla, MagneticFieldUnit.Millitesla, quantity => quantity.ToUnit(MagneticFieldUnit.Millitesla)); + unitConverter.SetConversionFunction<MagneticField>(MagneticFieldUnit.Tesla, MagneticFieldUnit.Nanotesla, quantity => quantity.ToUnit(MagneticFieldUnit.Nanotesla)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFieldUnit.Gauss, new CultureInfo("en-US"), false, true, new string[]{"G"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFieldUnit.Microtesla, new CultureInfo("en-US"), false, true, new string[]{"µT"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFieldUnit.Milligauss, new CultureInfo("en-US"), false, true, new string[]{"mG"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFieldUnit.Millitesla, new CultureInfo("en-US"), false, true, new string[]{"mT"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFieldUnit.Nanotesla, new CultureInfo("en-US"), false, true, new string[]{"nT"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFieldUnit.Tesla, new CultureInfo("en-US"), false, true, new string[]{"T"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MagneticFieldUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MagneticFieldUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MagneticField"/> from <see cref="MagneticFieldUnit.Gauss"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticField FromGausses(QuantityValue gausses) + { + double value = (double) gausses; + return new MagneticField(value, MagneticFieldUnit.Gauss); + } + + /// <summary> + /// Creates a <see cref="MagneticField"/> from <see cref="MagneticFieldUnit.Microtesla"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticField FromMicroteslas(QuantityValue microteslas) + { + double value = (double) microteslas; + return new MagneticField(value, MagneticFieldUnit.Microtesla); + } + + /// <summary> + /// Creates a <see cref="MagneticField"/> from <see cref="MagneticFieldUnit.Milligauss"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticField FromMilligausses(QuantityValue milligausses) + { + double value = (double) milligausses; + return new MagneticField(value, MagneticFieldUnit.Milligauss); + } + + /// <summary> + /// Creates a <see cref="MagneticField"/> from <see cref="MagneticFieldUnit.Millitesla"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticField FromMilliteslas(QuantityValue milliteslas) + { + double value = (double) milliteslas; + return new MagneticField(value, MagneticFieldUnit.Millitesla); + } + + /// <summary> + /// Creates a <see cref="MagneticField"/> from <see cref="MagneticFieldUnit.Nanotesla"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticField FromNanoteslas(QuantityValue nanoteslas) + { + double value = (double) nanoteslas; + return new MagneticField(value, MagneticFieldUnit.Nanotesla); + } + + /// <summary> + /// Creates a <see cref="MagneticField"/> from <see cref="MagneticFieldUnit.Tesla"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticField FromTeslas(QuantityValue teslas) + { + double value = (double) teslas; + return new MagneticField(value, MagneticFieldUnit.Tesla); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MagneticFieldUnit" /> to <see cref="MagneticField" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MagneticField unit value.</returns> + public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) + { + return new MagneticField((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MagneticField Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MagneticField Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MagneticField, MagneticFieldUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MagneticField result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MagneticField result) + { + return QuantityParser.Default.TryParse<MagneticField, MagneticFieldUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MagneticFieldUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MagneticFieldUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MagneticFieldUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MagneticFieldUnit)"/> + public static bool TryParseUnit(string str, out MagneticFieldUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MagneticFieldUnit unit) + { + return UnitParser.Default.TryParse<MagneticFieldUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MagneticField operator -(MagneticField right) + { + return new MagneticField(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MagneticField"/> from adding two <see cref="MagneticField"/>.</summary> + public static MagneticField operator +(MagneticField left, MagneticField right) + { + return new MagneticField(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MagneticField"/> from subtracting two <see cref="MagneticField"/>.</summary> + public static MagneticField operator -(MagneticField left, MagneticField right) + { + return new MagneticField(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MagneticField"/> from multiplying value and <see cref="MagneticField"/>.</summary> + public static MagneticField operator *(double left, MagneticField right) + { + return new MagneticField(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MagneticField"/> from multiplying value and <see cref="MagneticField"/>.</summary> + public static MagneticField operator *(MagneticField left, double right) + { + return new MagneticField(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MagneticField"/> from dividing <see cref="MagneticField"/> by value.</summary> + public static MagneticField operator /(MagneticField left, double right) + { + return new MagneticField(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MagneticField"/> by <see cref="MagneticField"/>.</summary> + public static double operator /(MagneticField left, MagneticField right) + { + return left.Teslas / right.Teslas; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MagneticField left, MagneticField right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MagneticField left, MagneticField right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MagneticField left, MagneticField right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MagneticField left, MagneticField right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MagneticField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MagneticField left, MagneticField right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MagneticField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MagneticField left, MagneticField right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MagneticField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MagneticField otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MagneticField"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticField, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MagneticField other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MagneticField"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MagneticField otherQuantity)) throw new ArgumentException("Expected type MagneticField.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MagneticField"/> with another <see cref="MagneticField"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MagneticField other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MagneticField within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MagneticField.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MagneticFieldUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MagneticFieldUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MagneticField to another MagneticField with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MagneticField with the specified unit.</returns> + public MagneticField ToUnit(MagneticFieldUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MagneticField"/> to another <see cref="MagneticField"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MagneticField with the specified unit.</returns> + public MagneticField ToUnit(MagneticFieldUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MagneticField), Unit, typeof(MagneticField), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MagneticField)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MagneticField"/> to another <see cref="MagneticField"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MagneticField"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MagneticFieldUnit unit, [NotNullWhen(true)] out MagneticField? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MagneticField? convertedOrNull = (Unit, unit) switch + { + // MagneticFieldUnit -> BaseUnit + (MagneticFieldUnit.Gauss, MagneticFieldUnit.Tesla) => new MagneticField(_value / 1e4, MagneticFieldUnit.Tesla), + (MagneticFieldUnit.Microtesla, MagneticFieldUnit.Tesla) => new MagneticField((_value) * 1e-6d, MagneticFieldUnit.Tesla), + (MagneticFieldUnit.Milligauss, MagneticFieldUnit.Tesla) => new MagneticField((_value / 1e4) * 1e-3d, MagneticFieldUnit.Tesla), + (MagneticFieldUnit.Millitesla, MagneticFieldUnit.Tesla) => new MagneticField((_value) * 1e-3d, MagneticFieldUnit.Tesla), + (MagneticFieldUnit.Nanotesla, MagneticFieldUnit.Tesla) => new MagneticField((_value) * 1e-9d, MagneticFieldUnit.Tesla), + + // BaseUnit -> MagneticFieldUnit + (MagneticFieldUnit.Tesla, MagneticFieldUnit.Gauss) => new MagneticField(_value * 1e4, MagneticFieldUnit.Gauss), + (MagneticFieldUnit.Tesla, MagneticFieldUnit.Microtesla) => new MagneticField((_value) / 1e-6d, MagneticFieldUnit.Microtesla), + (MagneticFieldUnit.Tesla, MagneticFieldUnit.Milligauss) => new MagneticField((_value * 1e4) / 1e-3d, MagneticFieldUnit.Milligauss), + (MagneticFieldUnit.Tesla, MagneticFieldUnit.Millitesla) => new MagneticField((_value) / 1e-3d, MagneticFieldUnit.Millitesla), + (MagneticFieldUnit.Tesla, MagneticFieldUnit.Nanotesla) => new MagneticField((_value) / 1e-9d, MagneticFieldUnit.Nanotesla), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MagneticFieldUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MagneticFieldUnit> IQuantity<MagneticFieldUnit>.ToUnit(MagneticFieldUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MagneticFieldUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MagneticField)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MagneticField)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MagneticField)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MagneticField)) + return this; + else if (conversionType == typeof(MagneticFieldUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MagneticField.Info; + else if (conversionType == typeof(BaseDimensions)) + return MagneticField.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MagneticField)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticFieldUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticFieldUnit.g.cs new file mode 100644 index 0000000000..3915ff523d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MagneticField/MagneticFieldUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MagneticFieldUnit + { + Gauss = 1, + Microtesla = 2, + Milligauss = 3, + Millitesla = 4, + Nanotesla = 5, + Tesla = 6, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFlux.csproj b/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFlux.csproj new file mode 100644 index 0000000000..2e568cc3ea --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFlux.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MagneticFlux</Title> + <Description>Adds MagneticFlux units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>magneticflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f0c5342b-fb95-48a4-029f-7aa631ce06f1}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MagneticFlux</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFlux.g.cs b/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFlux.g.cs new file mode 100644 index 0000000000..0c8b8e7636 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFlux.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Magnetic_flux + /// </remarks> + [DataContract] + public readonly partial struct MagneticFlux : IArithmeticQuantity<MagneticFlux, MagneticFluxUnit, double>, IEquatable<MagneticFlux>, IComparable, IComparable<MagneticFlux>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MagneticFluxUnit? _unit; + + static MagneticFlux() + { + BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); + BaseUnit = MagneticFluxUnit.Weber; + Units = Enum.GetValues(typeof(MagneticFluxUnit)).Cast<MagneticFluxUnit>().ToArray(); + Zero = new MagneticFlux(0, BaseUnit); + Info = new QuantityInfo<MagneticFluxUnit>("MagneticFlux", + new UnitInfo<MagneticFluxUnit>[] + { + new UnitInfo<MagneticFluxUnit>(MagneticFluxUnit.Weber, "Webers", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MagneticFlux(double value, MagneticFluxUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MagneticFlux" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MagneticFluxUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. + /// </summary> + public static MagneticFluxUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MagneticFlux quantity. + /// </summary> + public static MagneticFluxUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Weber. + /// </summary> + public static MagneticFlux Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MagneticFlux AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MagneticFluxUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagneticFluxUnit.Weber"/> + /// </summary> + public double Webers => As(MagneticFluxUnit.Weber); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MagneticFluxUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MagneticFlux>(MagneticFluxUnit.Weber, MagneticFluxUnit.Weber, quantity => quantity); + + // Register in unit converter: BaseUnit -> MagneticFluxUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MagneticFluxUnit.Weber, new CultureInfo("en-US"), false, true, new string[]{"Wb"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MagneticFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MagneticFluxUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MagneticFlux"/> from <see cref="MagneticFluxUnit.Weber"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MagneticFlux FromWebers(QuantityValue webers) + { + double value = (double) webers; + return new MagneticFlux(value, MagneticFluxUnit.Weber); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MagneticFluxUnit" /> to <see cref="MagneticFlux" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MagneticFlux unit value.</returns> + public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) + { + return new MagneticFlux((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MagneticFlux Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MagneticFlux Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MagneticFlux, MagneticFluxUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MagneticFlux result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MagneticFlux result) + { + return QuantityParser.Default.TryParse<MagneticFlux, MagneticFluxUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MagneticFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MagneticFluxUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MagneticFluxUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MagneticFluxUnit)"/> + public static bool TryParseUnit(string str, out MagneticFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MagneticFluxUnit unit) + { + return UnitParser.Default.TryParse<MagneticFluxUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MagneticFlux operator -(MagneticFlux right) + { + return new MagneticFlux(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MagneticFlux"/> from adding two <see cref="MagneticFlux"/>.</summary> + public static MagneticFlux operator +(MagneticFlux left, MagneticFlux right) + { + return new MagneticFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MagneticFlux"/> from subtracting two <see cref="MagneticFlux"/>.</summary> + public static MagneticFlux operator -(MagneticFlux left, MagneticFlux right) + { + return new MagneticFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MagneticFlux"/> from multiplying value and <see cref="MagneticFlux"/>.</summary> + public static MagneticFlux operator *(double left, MagneticFlux right) + { + return new MagneticFlux(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MagneticFlux"/> from multiplying value and <see cref="MagneticFlux"/>.</summary> + public static MagneticFlux operator *(MagneticFlux left, double right) + { + return new MagneticFlux(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MagneticFlux"/> from dividing <see cref="MagneticFlux"/> by value.</summary> + public static MagneticFlux operator /(MagneticFlux left, double right) + { + return new MagneticFlux(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MagneticFlux"/> by <see cref="MagneticFlux"/>.</summary> + public static double operator /(MagneticFlux left, MagneticFlux right) + { + return left.Webers / right.Webers; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MagneticFlux left, MagneticFlux right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MagneticFlux left, MagneticFlux right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MagneticFlux left, MagneticFlux right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MagneticFlux left, MagneticFlux right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MagneticFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MagneticFlux left, MagneticFlux right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MagneticFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MagneticFlux left, MagneticFlux right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MagneticFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MagneticFlux otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MagneticFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MagneticFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MagneticFlux other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MagneticFlux"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MagneticFlux otherQuantity)) throw new ArgumentException("Expected type MagneticFlux.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MagneticFlux"/> with another <see cref="MagneticFlux"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MagneticFlux other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MagneticFlux within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MagneticFlux.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MagneticFluxUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MagneticFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MagneticFlux to another MagneticFlux with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MagneticFlux with the specified unit.</returns> + public MagneticFlux ToUnit(MagneticFluxUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MagneticFlux"/> to another <see cref="MagneticFlux"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MagneticFlux with the specified unit.</returns> + public MagneticFlux ToUnit(MagneticFluxUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MagneticFlux), Unit, typeof(MagneticFlux), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MagneticFlux)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MagneticFlux"/> to another <see cref="MagneticFlux"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MagneticFlux"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MagneticFluxUnit unit, [NotNullWhen(true)] out MagneticFlux? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MagneticFlux? convertedOrNull = (Unit, unit) switch + { + // MagneticFluxUnit -> BaseUnit + + // BaseUnit -> MagneticFluxUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MagneticFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MagneticFluxUnit> IQuantity<MagneticFluxUnit>.ToUnit(MagneticFluxUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MagneticFluxUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MagneticFlux)) + return this; + else if (conversionType == typeof(MagneticFluxUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MagneticFlux.Info; + else if (conversionType == typeof(BaseDimensions)) + return MagneticFlux.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFluxUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFluxUnit.g.cs new file mode 100644 index 0000000000..e7f3635d2e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MagneticFlux/MagneticFluxUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MagneticFluxUnit + { + Weber = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Magnetization/Magnetization.csproj b/UnitsNet.Modular/GeneratedCode/Magnetization/Magnetization.csproj new file mode 100644 index 0000000000..6481ce9d55 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Magnetization/Magnetization.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Magnetization</Title> + <Description>Adds Magnetization units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>magnetization unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{3ea3301e-d3de-6979-f1d7-58352998951c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Magnetization</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Magnetization/Magnetization.g.cs b/UnitsNet.Modular/GeneratedCode/Magnetization/Magnetization.g.cs new file mode 100644 index 0000000000..b6d2818479 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Magnetization/Magnetization.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Magnetization + /// </remarks> + [DataContract] + public readonly partial struct Magnetization : IArithmeticQuantity<Magnetization, MagnetizationUnit, double>, IEquatable<Magnetization>, IComparable, IComparable<Magnetization>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MagnetizationUnit? _unit; + + static Magnetization() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); + BaseUnit = MagnetizationUnit.AmperePerMeter; + Units = Enum.GetValues(typeof(MagnetizationUnit)).Cast<MagnetizationUnit>().ToArray(); + Zero = new Magnetization(0, BaseUnit); + Info = new QuantityInfo<MagnetizationUnit>("Magnetization", + new UnitInfo<MagnetizationUnit>[] + { + new UnitInfo<MagnetizationUnit>(MagnetizationUnit.AmperePerMeter, "AmperesPerMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Magnetization(double value, MagnetizationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Magnetization" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MagnetizationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. + /// </summary> + public static MagnetizationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Magnetization quantity. + /// </summary> + public static MagnetizationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. + /// </summary> + public static Magnetization Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Magnetization AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MagnetizationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Magnetization.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MagnetizationUnit.AmperePerMeter"/> + /// </summary> + public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MagnetizationUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Magnetization>(MagnetizationUnit.AmperePerMeter, MagnetizationUnit.AmperePerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> MagnetizationUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MagnetizationUnit.AmperePerMeter, new CultureInfo("en-US"), false, true, new string[]{"A/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MagnetizationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MagnetizationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Magnetization"/> from <see cref="MagnetizationUnit.AmperePerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) + { + double value = (double) amperespermeter; + return new Magnetization(value, MagnetizationUnit.AmperePerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MagnetizationUnit" /> to <see cref="Magnetization" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Magnetization unit value.</returns> + public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) + { + return new Magnetization((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Magnetization Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Magnetization Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Magnetization, MagnetizationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Magnetization result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Magnetization result) + { + return QuantityParser.Default.TryParse<Magnetization, MagnetizationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MagnetizationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MagnetizationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MagnetizationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MagnetizationUnit)"/> + public static bool TryParseUnit(string str, out MagnetizationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MagnetizationUnit unit) + { + return UnitParser.Default.TryParse<MagnetizationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Magnetization operator -(Magnetization right) + { + return new Magnetization(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Magnetization"/> from adding two <see cref="Magnetization"/>.</summary> + public static Magnetization operator +(Magnetization left, Magnetization right) + { + return new Magnetization(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Magnetization"/> from subtracting two <see cref="Magnetization"/>.</summary> + public static Magnetization operator -(Magnetization left, Magnetization right) + { + return new Magnetization(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Magnetization"/> from multiplying value and <see cref="Magnetization"/>.</summary> + public static Magnetization operator *(double left, Magnetization right) + { + return new Magnetization(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Magnetization"/> from multiplying value and <see cref="Magnetization"/>.</summary> + public static Magnetization operator *(Magnetization left, double right) + { + return new Magnetization(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Magnetization"/> from dividing <see cref="Magnetization"/> by value.</summary> + public static Magnetization operator /(Magnetization left, double right) + { + return new Magnetization(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Magnetization"/> by <see cref="Magnetization"/>.</summary> + public static double operator /(Magnetization left, Magnetization right) + { + return left.AmperesPerMeter / right.AmperesPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Magnetization left, Magnetization right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Magnetization left, Magnetization right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Magnetization left, Magnetization right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Magnetization left, Magnetization right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Magnetization"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Magnetization, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Magnetization left, Magnetization right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Magnetization"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Magnetization, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Magnetization left, Magnetization right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Magnetization"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Magnetization, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Magnetization otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Magnetization"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Magnetization, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Magnetization other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Magnetization"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Magnetization otherQuantity)) throw new ArgumentException("Expected type Magnetization.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Magnetization"/> with another <see cref="Magnetization"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Magnetization other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Magnetization within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Magnetization.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MagnetizationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MagnetizationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Magnetization to another Magnetization with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Magnetization with the specified unit.</returns> + public Magnetization ToUnit(MagnetizationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Magnetization"/> to another <see cref="Magnetization"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Magnetization with the specified unit.</returns> + public Magnetization ToUnit(MagnetizationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Magnetization), Unit, typeof(Magnetization), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Magnetization)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Magnetization"/> to another <see cref="Magnetization"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Magnetization"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MagnetizationUnit unit, [NotNullWhen(true)] out Magnetization? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Magnetization? convertedOrNull = (Unit, unit) switch + { + // MagnetizationUnit -> BaseUnit + + // BaseUnit -> MagnetizationUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MagnetizationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MagnetizationUnit> IQuantity<MagnetizationUnit>.ToUnit(MagnetizationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MagnetizationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Magnetization)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Magnetization)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Magnetization)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Magnetization)) + return this; + else if (conversionType == typeof(MagnetizationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Magnetization.Info; + else if (conversionType == typeof(BaseDimensions)) + return Magnetization.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Magnetization)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Magnetization/MagnetizationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Magnetization/MagnetizationUnit.g.cs new file mode 100644 index 0000000000..956c88e2da --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Magnetization/MagnetizationUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MagnetizationUnit + { + AmperePerMeter = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Mass/Mass.csproj b/UnitsNet.Modular/GeneratedCode/Mass/Mass.csproj new file mode 100644 index 0000000000..73fd10af9e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Mass/Mass.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Mass</Title> + <Description>Adds Mass units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>mass unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f8c5a010-c353-31da-cadc-b56186be374f}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Mass</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Mass/Mass.g.cs b/UnitsNet.Modular/GeneratedCode/Mass/Mass.g.cs new file mode 100644 index 0000000000..47351f6e3d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Mass/Mass.g.cs @@ -0,0 +1,1377 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct Mass : IArithmeticQuantity<Mass, MassUnit, double>, IEquatable<Mass>, IComparable, IComparable<Mass>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MassUnit? _unit; + + static Mass() + { + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); + BaseUnit = MassUnit.Kilogram; + Units = Enum.GetValues(typeof(MassUnit)).Cast<MassUnit>().ToArray(); + Zero = new Mass(0, BaseUnit); + Info = new QuantityInfo<MassUnit>("Mass", + new UnitInfo<MassUnit>[] + { + new UnitInfo<MassUnit>(MassUnit.Centigram, "Centigrams", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Decagram, "Decagrams", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Decigram, "Decigrams", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.EarthMass, "EarthMasses", new BaseUnits(mass: MassUnit.EarthMass)), + new UnitInfo<MassUnit>(MassUnit.Grain, "Grains", new BaseUnits(mass: MassUnit.Grain)), + new UnitInfo<MassUnit>(MassUnit.Gram, "Grams", new BaseUnits(mass: MassUnit.Gram)), + new UnitInfo<MassUnit>(MassUnit.Hectogram, "Hectograms", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Kilogram, "Kilograms", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Kilopound, "Kilopounds", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Kilotonne, "Kilotonnes", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.LongHundredweight, "LongHundredweight", new BaseUnits(mass: MassUnit.LongHundredweight)), + new UnitInfo<MassUnit>(MassUnit.LongTon, "LongTons", new BaseUnits(mass: MassUnit.LongTon)), + new UnitInfo<MassUnit>(MassUnit.Megapound, "Megapounds", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Megatonne, "Megatonnes", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Microgram, "Micrograms", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Milligram, "Milligrams", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Nanogram, "Nanograms", BaseUnits.Undefined), + new UnitInfo<MassUnit>(MassUnit.Ounce, "Ounces", new BaseUnits(mass: MassUnit.Ounce)), + new UnitInfo<MassUnit>(MassUnit.Pound, "Pounds", new BaseUnits(mass: MassUnit.Pound)), + new UnitInfo<MassUnit>(MassUnit.ShortHundredweight, "ShortHundredweight", new BaseUnits(mass: MassUnit.ShortHundredweight)), + new UnitInfo<MassUnit>(MassUnit.ShortTon, "ShortTons", new BaseUnits(mass: MassUnit.ShortTon)), + new UnitInfo<MassUnit>(MassUnit.Slug, "Slugs", new BaseUnits(mass: MassUnit.Slug)), + new UnitInfo<MassUnit>(MassUnit.SolarMass, "SolarMasses", new BaseUnits(mass: MassUnit.SolarMass)), + new UnitInfo<MassUnit>(MassUnit.Stone, "Stone", new BaseUnits(mass: MassUnit.Stone)), + new UnitInfo<MassUnit>(MassUnit.Tonne, "Tonnes", new BaseUnits(mass: MassUnit.Tonne)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Mass(double value, MassUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Mass" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MassUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Mass, which is Kilogram. All conversions go via this value. + /// </summary> + public static MassUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Mass quantity. + /// </summary> + public static MassUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. + /// </summary> + public static Mass Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Mass AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MassUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Mass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Centigram"/> + /// </summary> + public double Centigrams => As(MassUnit.Centigram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Decagram"/> + /// </summary> + public double Decagrams => As(MassUnit.Decagram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Decigram"/> + /// </summary> + public double Decigrams => As(MassUnit.Decigram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.EarthMass"/> + /// </summary> + public double EarthMasses => As(MassUnit.EarthMass); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Grain"/> + /// </summary> + public double Grains => As(MassUnit.Grain); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Gram"/> + /// </summary> + public double Grams => As(MassUnit.Gram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Hectogram"/> + /// </summary> + public double Hectograms => As(MassUnit.Hectogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Kilogram"/> + /// </summary> + public double Kilograms => As(MassUnit.Kilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Kilopound"/> + /// </summary> + public double Kilopounds => As(MassUnit.Kilopound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Kilotonne"/> + /// </summary> + public double Kilotonnes => As(MassUnit.Kilotonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.LongHundredweight"/> + /// </summary> + public double LongHundredweight => As(MassUnit.LongHundredweight); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.LongTon"/> + /// </summary> + public double LongTons => As(MassUnit.LongTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Megapound"/> + /// </summary> + public double Megapounds => As(MassUnit.Megapound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Megatonne"/> + /// </summary> + public double Megatonnes => As(MassUnit.Megatonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Microgram"/> + /// </summary> + public double Micrograms => As(MassUnit.Microgram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Milligram"/> + /// </summary> + public double Milligrams => As(MassUnit.Milligram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Nanogram"/> + /// </summary> + public double Nanograms => As(MassUnit.Nanogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Ounce"/> + /// </summary> + public double Ounces => As(MassUnit.Ounce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Pound"/> + /// </summary> + public double Pounds => As(MassUnit.Pound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.ShortHundredweight"/> + /// </summary> + public double ShortHundredweight => As(MassUnit.ShortHundredweight); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.ShortTon"/> + /// </summary> + public double ShortTons => As(MassUnit.ShortTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Slug"/> + /// </summary> + public double Slugs => As(MassUnit.Slug); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.SolarMass"/> + /// </summary> + public double SolarMasses => As(MassUnit.SolarMass); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Stone"/> + /// </summary> + public double Stone => As(MassUnit.Stone); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassUnit.Tonne"/> + /// </summary> + public double Tonnes => As(MassUnit.Tonne); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MassUnit -> BaseUnit + unitConverter.SetConversionFunction<Mass>(MassUnit.Centigram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Decagram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Decigram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.EarthMass, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Grain, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Gram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Hectogram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilopound, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilotonne, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.LongHundredweight, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.LongTon, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Megapound, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Megatonne, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Microgram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Milligram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Nanogram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Ounce, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Pound, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.ShortHundredweight, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.ShortTon, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Slug, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.SolarMass, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Stone, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Tonne, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Kilogram, quantity => quantity); + + // Register in unit converter: BaseUnit -> MassUnit + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Centigram, quantity => quantity.ToUnit(MassUnit.Centigram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Decagram, quantity => quantity.ToUnit(MassUnit.Decagram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Decigram, quantity => quantity.ToUnit(MassUnit.Decigram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.EarthMass, quantity => quantity.ToUnit(MassUnit.EarthMass)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Grain, quantity => quantity.ToUnit(MassUnit.Grain)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Gram, quantity => quantity.ToUnit(MassUnit.Gram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Hectogram, quantity => quantity.ToUnit(MassUnit.Hectogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Kilopound, quantity => quantity.ToUnit(MassUnit.Kilopound)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Kilotonne, quantity => quantity.ToUnit(MassUnit.Kilotonne)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.LongHundredweight, quantity => quantity.ToUnit(MassUnit.LongHundredweight)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.LongTon, quantity => quantity.ToUnit(MassUnit.LongTon)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Megapound, quantity => quantity.ToUnit(MassUnit.Megapound)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Megatonne, quantity => quantity.ToUnit(MassUnit.Megatonne)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Microgram, quantity => quantity.ToUnit(MassUnit.Microgram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Milligram, quantity => quantity.ToUnit(MassUnit.Milligram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Nanogram, quantity => quantity.ToUnit(MassUnit.Nanogram)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Ounce, quantity => quantity.ToUnit(MassUnit.Ounce)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Pound, quantity => quantity.ToUnit(MassUnit.Pound)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.ShortHundredweight, quantity => quantity.ToUnit(MassUnit.ShortHundredweight)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.ShortTon, quantity => quantity.ToUnit(MassUnit.ShortTon)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Slug, quantity => quantity.ToUnit(MassUnit.Slug)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.SolarMass, quantity => quantity.ToUnit(MassUnit.SolarMass)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Stone, quantity => quantity.ToUnit(MassUnit.Stone)); + unitConverter.SetConversionFunction<Mass>(MassUnit.Kilogram, MassUnit.Tonne, quantity => quantity.ToUnit(MassUnit.Tonne)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Centigram, new CultureInfo("en-US"), false, true, new string[]{"cg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Centigram, new CultureInfo("ru-RU"), false, true, new string[]{"сг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Centigram, new CultureInfo("zh-CN"), false, true, new string[]{"厘克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Decagram, new CultureInfo("en-US"), false, true, new string[]{"dag"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Decagram, new CultureInfo("ru-RU"), false, true, new string[]{"даг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Decagram, new CultureInfo("zh-CN"), false, true, new string[]{"十克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Decigram, new CultureInfo("en-US"), false, true, new string[]{"dg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Decigram, new CultureInfo("ru-RU"), false, true, new string[]{"дг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Decigram, new CultureInfo("zh-CN"), false, true, new string[]{"分克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.EarthMass, new CultureInfo("en-US"), false, true, new string[]{"em"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Grain, new CultureInfo("en-US"), false, true, new string[]{"gr"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Gram, new CultureInfo("en-US"), false, true, new string[]{"g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Gram, new CultureInfo("ru-RU"), false, true, new string[]{"г"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Gram, new CultureInfo("zh-CN"), false, true, new string[]{"克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Hectogram, new CultureInfo("en-US"), false, true, new string[]{"hg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Hectogram, new CultureInfo("ru-RU"), false, true, new string[]{"гг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Hectogram, new CultureInfo("zh-CN"), false, true, new string[]{"百克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilogram, new CultureInfo("en-US"), false, true, new string[]{"kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilogram, new CultureInfo("ru-RU"), false, true, new string[]{"кг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilogram, new CultureInfo("zh-CN"), false, true, new string[]{"千克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilopound, new CultureInfo("en-US"), false, true, new string[]{"klb", "klbs", "klbm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilopound, new CultureInfo("ru-RU"), false, true, new string[]{"кфунт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilopound, new CultureInfo("zh-CN"), false, true, new string[]{"千磅"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilotonne, new CultureInfo("en-US"), false, true, new string[]{"kt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilotonne, new CultureInfo("ru-RU"), false, true, new string[]{"кт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Kilotonne, new CultureInfo("zh-CN"), false, true, new string[]{"千吨"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.LongHundredweight, new CultureInfo("en-US"), false, true, new string[]{"cwt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.LongTon, new CultureInfo("en-US"), false, true, new string[]{"long tn"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.LongTon, new CultureInfo("ru-RU"), false, true, new string[]{"тонна большая"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.LongTon, new CultureInfo("zh-CN"), false, true, new string[]{"长吨"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Megapound, new CultureInfo("en-US"), false, true, new string[]{"Mlb", "Mlbs", "Mlbm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Megapound, new CultureInfo("ru-RU"), false, true, new string[]{"Мфунт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Megapound, new CultureInfo("zh-CN"), false, true, new string[]{"兆磅"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Megatonne, new CultureInfo("en-US"), false, true, new string[]{"Mt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Megatonne, new CultureInfo("ru-RU"), false, true, new string[]{"Мт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Megatonne, new CultureInfo("zh-CN"), false, true, new string[]{"兆吨"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Microgram, new CultureInfo("en-US"), false, true, new string[]{"µg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Microgram, new CultureInfo("ru-RU"), false, true, new string[]{"мкг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Microgram, new CultureInfo("zh-CN"), false, true, new string[]{"微克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Milligram, new CultureInfo("en-US"), false, true, new string[]{"mg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Milligram, new CultureInfo("ru-RU"), false, true, new string[]{"мг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Milligram, new CultureInfo("zh-CN"), false, true, new string[]{"毫克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Nanogram, new CultureInfo("en-US"), false, true, new string[]{"ng"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Nanogram, new CultureInfo("ru-RU"), false, true, new string[]{"нг"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Nanogram, new CultureInfo("zh-CN"), false, true, new string[]{"纳克"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Ounce, new CultureInfo("en-US"), false, true, new string[]{"oz"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Ounce, new CultureInfo("zh-CN"), false, true, new string[]{"盎司"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Pound, new CultureInfo("en-US"), false, true, new string[]{"lb", "lbs", "lbm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Pound, new CultureInfo("ru-RU"), false, true, new string[]{"фунт"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Pound, new CultureInfo("zh-CN"), false, true, new string[]{"磅"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.ShortHundredweight, new CultureInfo("en-US"), false, true, new string[]{"cwt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.ShortTon, new CultureInfo("en-US"), false, true, new string[]{"t (short)", "short tn", "ST"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.ShortTon, new CultureInfo("ru-RU"), false, true, new string[]{"тонна малая"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.ShortTon, new CultureInfo("zh-CN"), false, true, new string[]{"短吨"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Slug, new CultureInfo("en-US"), false, true, new string[]{"slug"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.SolarMass, new CultureInfo("en-US"), false, true, new string[]{"M☉", "M⊙"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Stone, new CultureInfo("en-US"), false, true, new string[]{"st"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Tonne, new CultureInfo("en-US"), false, true, new string[]{"t"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Tonne, new CultureInfo("ru-RU"), false, true, new string[]{"т"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassUnit.Tonne, new CultureInfo("zh-CN"), false, true, new string[]{"吨"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MassUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MassUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Centigram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromCentigrams(QuantityValue centigrams) + { + double value = (double) centigrams; + return new Mass(value, MassUnit.Centigram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Decagram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromDecagrams(QuantityValue decagrams) + { + double value = (double) decagrams; + return new Mass(value, MassUnit.Decagram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Decigram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromDecigrams(QuantityValue decigrams) + { + double value = (double) decigrams; + return new Mass(value, MassUnit.Decigram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.EarthMass"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromEarthMasses(QuantityValue earthmasses) + { + double value = (double) earthmasses; + return new Mass(value, MassUnit.EarthMass); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Grain"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromGrains(QuantityValue grains) + { + double value = (double) grains; + return new Mass(value, MassUnit.Grain); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Gram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromGrams(QuantityValue grams) + { + double value = (double) grams; + return new Mass(value, MassUnit.Gram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Hectogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromHectograms(QuantityValue hectograms) + { + double value = (double) hectograms; + return new Mass(value, MassUnit.Hectogram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Kilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromKilograms(QuantityValue kilograms) + { + double value = (double) kilograms; + return new Mass(value, MassUnit.Kilogram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Kilopound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromKilopounds(QuantityValue kilopounds) + { + double value = (double) kilopounds; + return new Mass(value, MassUnit.Kilopound); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Kilotonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromKilotonnes(QuantityValue kilotonnes) + { + double value = (double) kilotonnes; + return new Mass(value, MassUnit.Kilotonne); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.LongHundredweight"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromLongHundredweight(QuantityValue longhundredweight) + { + double value = (double) longhundredweight; + return new Mass(value, MassUnit.LongHundredweight); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.LongTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromLongTons(QuantityValue longtons) + { + double value = (double) longtons; + return new Mass(value, MassUnit.LongTon); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Megapound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromMegapounds(QuantityValue megapounds) + { + double value = (double) megapounds; + return new Mass(value, MassUnit.Megapound); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Megatonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromMegatonnes(QuantityValue megatonnes) + { + double value = (double) megatonnes; + return new Mass(value, MassUnit.Megatonne); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Microgram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromMicrograms(QuantityValue micrograms) + { + double value = (double) micrograms; + return new Mass(value, MassUnit.Microgram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Milligram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromMilligrams(QuantityValue milligrams) + { + double value = (double) milligrams; + return new Mass(value, MassUnit.Milligram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Nanogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromNanograms(QuantityValue nanograms) + { + double value = (double) nanograms; + return new Mass(value, MassUnit.Nanogram); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Ounce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromOunces(QuantityValue ounces) + { + double value = (double) ounces; + return new Mass(value, MassUnit.Ounce); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Pound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromPounds(QuantityValue pounds) + { + double value = (double) pounds; + return new Mass(value, MassUnit.Pound); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.ShortHundredweight"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromShortHundredweight(QuantityValue shorthundredweight) + { + double value = (double) shorthundredweight; + return new Mass(value, MassUnit.ShortHundredweight); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.ShortTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromShortTons(QuantityValue shorttons) + { + double value = (double) shorttons; + return new Mass(value, MassUnit.ShortTon); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Slug"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromSlugs(QuantityValue slugs) + { + double value = (double) slugs; + return new Mass(value, MassUnit.Slug); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.SolarMass"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromSolarMasses(QuantityValue solarmasses) + { + double value = (double) solarmasses; + return new Mass(value, MassUnit.SolarMass); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Stone"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromStone(QuantityValue stone) + { + double value = (double) stone; + return new Mass(value, MassUnit.Stone); + } + + /// <summary> + /// Creates a <see cref="Mass"/> from <see cref="MassUnit.Tonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Mass FromTonnes(QuantityValue tonnes) + { + double value = (double) tonnes; + return new Mass(value, MassUnit.Tonne); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MassUnit" /> to <see cref="Mass" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Mass unit value.</returns> + public static Mass From(QuantityValue value, MassUnit fromUnit) + { + return new Mass((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Mass Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Mass Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Mass, MassUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Mass result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Mass result) + { + return QuantityParser.Default.TryParse<Mass, MassUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MassUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MassUnit)"/> + public static bool TryParseUnit(string str, out MassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MassUnit unit) + { + return UnitParser.Default.TryParse<MassUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Mass operator -(Mass right) + { + return new Mass(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Mass"/> from adding two <see cref="Mass"/>.</summary> + public static Mass operator +(Mass left, Mass right) + { + return new Mass(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Mass"/> from subtracting two <see cref="Mass"/>.</summary> + public static Mass operator -(Mass left, Mass right) + { + return new Mass(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Mass"/> from multiplying value and <see cref="Mass"/>.</summary> + public static Mass operator *(double left, Mass right) + { + return new Mass(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Mass"/> from multiplying value and <see cref="Mass"/>.</summary> + public static Mass operator *(Mass left, double right) + { + return new Mass(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Mass"/> from dividing <see cref="Mass"/> by value.</summary> + public static Mass operator /(Mass left, double right) + { + return new Mass(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Mass"/> by <see cref="Mass"/>.</summary> + public static double operator /(Mass left, Mass right) + { + return left.Kilograms / right.Kilograms; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Mass left, Mass right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Mass left, Mass right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Mass left, Mass right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Mass left, Mass right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Mass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Mass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Mass left, Mass right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Mass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Mass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Mass left, Mass right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Mass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Mass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Mass otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Mass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Mass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Mass other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Mass"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Mass otherQuantity)) throw new ArgumentException("Expected type Mass.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Mass"/> with another <see cref="Mass"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Mass other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Mass within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Mass.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MassUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MassUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Mass to another Mass with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Mass with the specified unit.</returns> + public Mass ToUnit(MassUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Mass"/> to another <see cref="Mass"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Mass with the specified unit.</returns> + public Mass ToUnit(MassUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Mass), Unit, typeof(Mass), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Mass)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Mass"/> to another <see cref="Mass"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Mass"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MassUnit unit, [NotNullWhen(true)] out Mass? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Mass? convertedOrNull = (Unit, unit) switch + { + // MassUnit -> BaseUnit + (MassUnit.Centigram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-2d, MassUnit.Kilogram), + (MassUnit.Decagram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e1d, MassUnit.Kilogram), + (MassUnit.Decigram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-1d, MassUnit.Kilogram), + (MassUnit.EarthMass, MassUnit.Kilogram) => new Mass(_value * 5.9722E+24, MassUnit.Kilogram), + (MassUnit.Grain, MassUnit.Kilogram) => new Mass(_value / 15432.358352941431, MassUnit.Kilogram), + (MassUnit.Gram, MassUnit.Kilogram) => new Mass(_value / 1e3, MassUnit.Kilogram), + (MassUnit.Hectogram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e2d, MassUnit.Kilogram), + (MassUnit.Kilopound, MassUnit.Kilogram) => new Mass((_value * 0.45359237) * 1e3d, MassUnit.Kilogram), + (MassUnit.Kilotonne, MassUnit.Kilogram) => new Mass((_value * 1e3) * 1e3d, MassUnit.Kilogram), + (MassUnit.LongHundredweight, MassUnit.Kilogram) => new Mass(_value / 0.01968413055222121, MassUnit.Kilogram), + (MassUnit.LongTon, MassUnit.Kilogram) => new Mass(_value * 1.0160469088e3, MassUnit.Kilogram), + (MassUnit.Megapound, MassUnit.Kilogram) => new Mass((_value * 0.45359237) * 1e6d, MassUnit.Kilogram), + (MassUnit.Megatonne, MassUnit.Kilogram) => new Mass((_value * 1e3) * 1e6d, MassUnit.Kilogram), + (MassUnit.Microgram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-6d, MassUnit.Kilogram), + (MassUnit.Milligram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-3d, MassUnit.Kilogram), + (MassUnit.Nanogram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-9d, MassUnit.Kilogram), + (MassUnit.Ounce, MassUnit.Kilogram) => new Mass(_value / 35.2739619, MassUnit.Kilogram), + (MassUnit.Pound, MassUnit.Kilogram) => new Mass(_value * 0.45359237, MassUnit.Kilogram), + (MassUnit.ShortHundredweight, MassUnit.Kilogram) => new Mass(_value / 0.022046226218487758, MassUnit.Kilogram), + (MassUnit.ShortTon, MassUnit.Kilogram) => new Mass(_value * 9.0718474e2, MassUnit.Kilogram), + (MassUnit.Slug, MassUnit.Kilogram) => new Mass(_value / 6.852176556196105e-2, MassUnit.Kilogram), + (MassUnit.SolarMass, MassUnit.Kilogram) => new Mass(_value * 1.98947e30, MassUnit.Kilogram), + (MassUnit.Stone, MassUnit.Kilogram) => new Mass(_value / 0.1574731728702698, MassUnit.Kilogram), + (MassUnit.Tonne, MassUnit.Kilogram) => new Mass(_value * 1e3, MassUnit.Kilogram), + + // BaseUnit -> MassUnit + (MassUnit.Kilogram, MassUnit.Centigram) => new Mass((_value * 1e3) / 1e-2d, MassUnit.Centigram), + (MassUnit.Kilogram, MassUnit.Decagram) => new Mass((_value * 1e3) / 1e1d, MassUnit.Decagram), + (MassUnit.Kilogram, MassUnit.Decigram) => new Mass((_value * 1e3) / 1e-1d, MassUnit.Decigram), + (MassUnit.Kilogram, MassUnit.EarthMass) => new Mass(_value / 5.9722E+24, MassUnit.EarthMass), + (MassUnit.Kilogram, MassUnit.Grain) => new Mass(_value * 15432.358352941431, MassUnit.Grain), + (MassUnit.Kilogram, MassUnit.Gram) => new Mass(_value * 1e3, MassUnit.Gram), + (MassUnit.Kilogram, MassUnit.Hectogram) => new Mass((_value * 1e3) / 1e2d, MassUnit.Hectogram), + (MassUnit.Kilogram, MassUnit.Kilopound) => new Mass((_value / 0.45359237) / 1e3d, MassUnit.Kilopound), + (MassUnit.Kilogram, MassUnit.Kilotonne) => new Mass((_value / 1e3) / 1e3d, MassUnit.Kilotonne), + (MassUnit.Kilogram, MassUnit.LongHundredweight) => new Mass(_value * 0.01968413055222121, MassUnit.LongHundredweight), + (MassUnit.Kilogram, MassUnit.LongTon) => new Mass(_value / 1.0160469088e3, MassUnit.LongTon), + (MassUnit.Kilogram, MassUnit.Megapound) => new Mass((_value / 0.45359237) / 1e6d, MassUnit.Megapound), + (MassUnit.Kilogram, MassUnit.Megatonne) => new Mass((_value / 1e3) / 1e6d, MassUnit.Megatonne), + (MassUnit.Kilogram, MassUnit.Microgram) => new Mass((_value * 1e3) / 1e-6d, MassUnit.Microgram), + (MassUnit.Kilogram, MassUnit.Milligram) => new Mass((_value * 1e3) / 1e-3d, MassUnit.Milligram), + (MassUnit.Kilogram, MassUnit.Nanogram) => new Mass((_value * 1e3) / 1e-9d, MassUnit.Nanogram), + (MassUnit.Kilogram, MassUnit.Ounce) => new Mass(_value * 35.2739619, MassUnit.Ounce), + (MassUnit.Kilogram, MassUnit.Pound) => new Mass(_value / 0.45359237, MassUnit.Pound), + (MassUnit.Kilogram, MassUnit.ShortHundredweight) => new Mass(_value * 0.022046226218487758, MassUnit.ShortHundredweight), + (MassUnit.Kilogram, MassUnit.ShortTon) => new Mass(_value / 9.0718474e2, MassUnit.ShortTon), + (MassUnit.Kilogram, MassUnit.Slug) => new Mass(_value * 6.852176556196105e-2, MassUnit.Slug), + (MassUnit.Kilogram, MassUnit.SolarMass) => new Mass(_value / 1.98947e30, MassUnit.SolarMass), + (MassUnit.Kilogram, MassUnit.Stone) => new Mass(_value * 0.1574731728702698, MassUnit.Stone), + (MassUnit.Kilogram, MassUnit.Tonne) => new Mass(_value / 1e3, MassUnit.Tonne), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MassUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MassUnit> IQuantity<MassUnit>.ToUnit(MassUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MassUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Mass)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Mass)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Mass)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Mass)) + return this; + else if (conversionType == typeof(MassUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Mass.Info; + else if (conversionType == typeof(BaseDimensions)) + return Mass.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Mass)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Mass/MassUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Mass/MassUnit.g.cs new file mode 100644 index 0000000000..5cf1e962b4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Mass/MassUnit.g.cs @@ -0,0 +1,110 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MassUnit + { + Centigram = 1, + Decagram = 2, + Decigram = 3, + + /// <summary> + /// Earth mass is a ratio unit to the mass of planet Earth. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Earth_mass</remarks> + EarthMass = 4, + + /// <summary> + /// A grain is a unit of measurement of mass, and in the troy weight, avoirdupois, and Apothecaries' system, equal to exactly 64.79891 milligrams. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Grain_(unit)</remarks> + Grain = 5, + Gram = 6, + Hectogram = 7, + Kilogram = 8, + Kilopound = 9, + Kilotonne = 10, + + /// <summary> + /// The long or imperial hundredweight (abbreviation cwt) is a unit of mass equal to 112 pounds in US and Canada. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Hundredweight</remarks> + LongHundredweight = 11, + + /// <summary> + /// Long ton (weight ton or Imperial ton) is a unit of mass equal to 2,240 pounds (1,016 kg) and is the name for the unit called the "ton" in the avoirdupois or Imperial system of measurements that was used in the United Kingdom and several other Commonwealth countries before metrication. + /// </summary> + /// <remarks>http://en.wikipedia.org/wiki/Long_ton</remarks> + LongTon = 12, + Megapound = 13, + Megatonne = 14, + Microgram = 15, + Milligram = 16, + Nanogram = 17, + + /// <summary> + /// An ounce (abbreviated oz) is usually the international avoirdupois ounce as used in the United States customary and British imperial systems, which is equal to one-sixteenth of a pound or approximately 28 grams. The abbreviation 'oz' derives from the Italian word onza (now spelled oncia). + /// </summary> + /// <remarks>http://en.wikipedia.org/wiki/Ounce</remarks> + Ounce = 18, + + /// <summary> + /// The pound or pound-mass (abbreviations: lb, lbm) is a unit of mass used in the imperial, United States customary and other systems of measurement. A number of different definitions have been used, the most common today being the international avoirdupois pound which is legally defined as exactly 0.45359237 kilograms, and which is divided into 16 avoirdupois ounces. + /// </summary> + Pound = 19, + + /// <summary> + /// The short hundredweight (abbreviation cwt) is a unit of mass equal to 100 pounds in US and Canada. In British English, the short hundredweight is referred to as the "cental". + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Hundredweight</remarks> + ShortHundredweight = 20, + + /// <summary> + /// The short ton is a unit of mass equal to 2,000 pounds (907.18474 kg), that is most commonly used in the United States – known there simply as the ton. + /// </summary> + /// <remarks>http://en.wikipedia.org/wiki/Short_ton</remarks> + ShortTon = 21, + + /// <summary> + /// The slug (abbreviation slug) is a unit of mass that is accelerated by 1 ft/s² when a force of one pound (lbf) is exerted on it. + /// </summary> + /// <remarks>http://en.wikipedia.org/wiki/Slug_(unit)</remarks> + Slug = 22, + + /// <summary> + /// Solar mass is a ratio unit to the mass of the solar system star, the sun. + /// </summary> + /// <remarks>https://en.wikipedia.org/wiki/Solar_mass</remarks> + SolarMass = 23, + + /// <summary> + /// The stone (abbreviation st) is a unit of mass equal to 14 pounds avoirdupois (about 6.35 kilograms) used in Great Britain and Ireland for measuring human body weight. + /// </summary> + /// <remarks>http://en.wikipedia.org/wiki/Stone_(unit)</remarks> + Stone = 24, + Tonne = 25, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentration.csproj b/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentration.csproj new file mode 100644 index 0000000000..c3a1769ec3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentration.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MassConcentration</Title> + <Description>Adds MassConcentration units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>massconcentration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{0b1482c2-a3b1-6207-b73f-a07f46718b65}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MassConcentration</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentration.g.cs b/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentration.g.cs new file mode 100644 index 0000000000..c43fadac8a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentration.g.cs @@ -0,0 +1,1853 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In chemistry, the mass concentration ρi (or γi) is defined as the mass of a constituent mi divided by the volume of the mixture V + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Mass_concentration_(chemistry) + /// </remarks> + [DataContract] + public readonly partial struct MassConcentration : IArithmeticQuantity<MassConcentration, MassConcentrationUnit, double>, IEquatable<MassConcentration>, IComparable, IComparable<MassConcentration>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MassConcentrationUnit? _unit; + + static MassConcentration() + { + BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); + BaseUnit = MassConcentrationUnit.KilogramPerCubicMeter; + Units = Enum.GetValues(typeof(MassConcentrationUnit)).Cast<MassConcentrationUnit>().ToArray(); + Zero = new MassConcentration(0, BaseUnit); + Info = new QuantityInfo<MassConcentrationUnit>("MassConcentration", + new UnitInfo<MassConcentrationUnit>[] + { + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.CentigramPerDeciliter, "CentigramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.CentigramPerLiter, "CentigramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.CentigramPerMicroliter, "CentigramsPerMicroliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.CentigramPerMilliliter, "CentigramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.DecigramPerDeciliter, "DecigramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.DecigramPerLiter, "DecigramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.DecigramPerMicroliter, "DecigramsPerMicroliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.DecigramPerMilliliter, "DecigramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerCubicCentimeter, "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerCubicMeter, "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerCubicMillimeter, "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerDeciliter, "GramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerLiter, "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerMicroliter, "GramsPerMicroliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.GramPerMilliliter, "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.KilogramPerCubicCentimeter, "KilogramsPerCubicCentimeter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.KilogramPerCubicMeter, "KilogramsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.KilogramPerCubicMillimeter, "KilogramsPerCubicMillimeter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.KilogramPerLiter, "KilogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.KilopoundPerCubicFoot, "KilopoundsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.KilopoundPerCubicInch, "KilopoundsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MicrogramPerCubicMeter, "MicrogramsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MicrogramPerDeciliter, "MicrogramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MicrogramPerLiter, "MicrogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MicrogramPerMicroliter, "MicrogramsPerMicroliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MicrogramPerMilliliter, "MicrogramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MilligramPerCubicMeter, "MilligramsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MilligramPerDeciliter, "MilligramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MilligramPerLiter, "MilligramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MilligramPerMicroliter, "MilligramsPerMicroliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.MilligramPerMilliliter, "MilligramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.NanogramPerDeciliter, "NanogramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.NanogramPerLiter, "NanogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.NanogramPerMicroliter, "NanogramsPerMicroliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.NanogramPerMilliliter, "NanogramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.OuncePerImperialGallon, "OuncesPerImperialGallon", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.OuncePerUSGallon, "OuncesPerUSGallon", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PicogramPerDeciliter, "PicogramsPerDeciliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PicogramPerLiter, "PicogramsPerLiter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PicogramPerMicroliter, "PicogramsPerMicroliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PicogramPerMilliliter, "PicogramsPerMilliliter", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PoundPerCubicFoot, "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PoundPerCubicInch, "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PoundPerImperialGallon, "PoundsPerImperialGallon", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.PoundPerUSGallon, "PoundsPerUSGallon", BaseUnits.Undefined), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.SlugPerCubicFoot, "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.TonnePerCubicCentimeter, "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.TonnePerCubicMeter, "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)), + new UnitInfo<MassConcentrationUnit>(MassConcentrationUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MassConcentration(double value, MassConcentrationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MassConcentration" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MassConcentrationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MassConcentration, which is KilogramPerCubicMeter. All conversions go via this value. + /// </summary> + public static MassConcentrationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MassConcentration quantity. + /// </summary> + public static MassConcentrationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. + /// </summary> + public static MassConcentration Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MassConcentration AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MassConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MassConcentrationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MassConcentration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.CentigramPerDeciliter"/> + /// </summary> + public double CentigramsPerDeciliter => As(MassConcentrationUnit.CentigramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.CentigramPerLiter"/> + /// </summary> + public double CentigramsPerLiter => As(MassConcentrationUnit.CentigramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.CentigramPerMicroliter"/> + /// </summary> + public double CentigramsPerMicroliter => As(MassConcentrationUnit.CentigramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.CentigramPerMilliliter"/> + /// </summary> + public double CentigramsPerMilliliter => As(MassConcentrationUnit.CentigramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.DecigramPerDeciliter"/> + /// </summary> + public double DecigramsPerDeciliter => As(MassConcentrationUnit.DecigramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.DecigramPerLiter"/> + /// </summary> + public double DecigramsPerLiter => As(MassConcentrationUnit.DecigramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.DecigramPerMicroliter"/> + /// </summary> + public double DecigramsPerMicroliter => As(MassConcentrationUnit.DecigramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.DecigramPerMilliliter"/> + /// </summary> + public double DecigramsPerMilliliter => As(MassConcentrationUnit.DecigramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerCubicCentimeter"/> + /// </summary> + public double GramsPerCubicCentimeter => As(MassConcentrationUnit.GramPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerCubicMeter"/> + /// </summary> + public double GramsPerCubicMeter => As(MassConcentrationUnit.GramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerCubicMillimeter"/> + /// </summary> + public double GramsPerCubicMillimeter => As(MassConcentrationUnit.GramPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerDeciliter"/> + /// </summary> + public double GramsPerDeciliter => As(MassConcentrationUnit.GramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerLiter"/> + /// </summary> + public double GramsPerLiter => As(MassConcentrationUnit.GramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerMicroliter"/> + /// </summary> + public double GramsPerMicroliter => As(MassConcentrationUnit.GramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.GramPerMilliliter"/> + /// </summary> + public double GramsPerMilliliter => As(MassConcentrationUnit.GramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.KilogramPerCubicCentimeter"/> + /// </summary> + public double KilogramsPerCubicCentimeter => As(MassConcentrationUnit.KilogramPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.KilogramPerCubicMeter"/> + /// </summary> + public double KilogramsPerCubicMeter => As(MassConcentrationUnit.KilogramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.KilogramPerCubicMillimeter"/> + /// </summary> + public double KilogramsPerCubicMillimeter => As(MassConcentrationUnit.KilogramPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.KilogramPerLiter"/> + /// </summary> + public double KilogramsPerLiter => As(MassConcentrationUnit.KilogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.KilopoundPerCubicFoot"/> + /// </summary> + public double KilopoundsPerCubicFoot => As(MassConcentrationUnit.KilopoundPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.KilopoundPerCubicInch"/> + /// </summary> + public double KilopoundsPerCubicInch => As(MassConcentrationUnit.KilopoundPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MicrogramPerCubicMeter"/> + /// </summary> + public double MicrogramsPerCubicMeter => As(MassConcentrationUnit.MicrogramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MicrogramPerDeciliter"/> + /// </summary> + public double MicrogramsPerDeciliter => As(MassConcentrationUnit.MicrogramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MicrogramPerLiter"/> + /// </summary> + public double MicrogramsPerLiter => As(MassConcentrationUnit.MicrogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MicrogramPerMicroliter"/> + /// </summary> + public double MicrogramsPerMicroliter => As(MassConcentrationUnit.MicrogramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MicrogramPerMilliliter"/> + /// </summary> + public double MicrogramsPerMilliliter => As(MassConcentrationUnit.MicrogramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MilligramPerCubicMeter"/> + /// </summary> + public double MilligramsPerCubicMeter => As(MassConcentrationUnit.MilligramPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MilligramPerDeciliter"/> + /// </summary> + public double MilligramsPerDeciliter => As(MassConcentrationUnit.MilligramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MilligramPerLiter"/> + /// </summary> + public double MilligramsPerLiter => As(MassConcentrationUnit.MilligramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MilligramPerMicroliter"/> + /// </summary> + public double MilligramsPerMicroliter => As(MassConcentrationUnit.MilligramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.MilligramPerMilliliter"/> + /// </summary> + public double MilligramsPerMilliliter => As(MassConcentrationUnit.MilligramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.NanogramPerDeciliter"/> + /// </summary> + public double NanogramsPerDeciliter => As(MassConcentrationUnit.NanogramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.NanogramPerLiter"/> + /// </summary> + public double NanogramsPerLiter => As(MassConcentrationUnit.NanogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.NanogramPerMicroliter"/> + /// </summary> + public double NanogramsPerMicroliter => As(MassConcentrationUnit.NanogramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.NanogramPerMilliliter"/> + /// </summary> + public double NanogramsPerMilliliter => As(MassConcentrationUnit.NanogramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.OuncePerImperialGallon"/> + /// </summary> + public double OuncesPerImperialGallon => As(MassConcentrationUnit.OuncePerImperialGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.OuncePerUSGallon"/> + /// </summary> + public double OuncesPerUSGallon => As(MassConcentrationUnit.OuncePerUSGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PicogramPerDeciliter"/> + /// </summary> + public double PicogramsPerDeciliter => As(MassConcentrationUnit.PicogramPerDeciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PicogramPerLiter"/> + /// </summary> + public double PicogramsPerLiter => As(MassConcentrationUnit.PicogramPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PicogramPerMicroliter"/> + /// </summary> + public double PicogramsPerMicroliter => As(MassConcentrationUnit.PicogramPerMicroliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PicogramPerMilliliter"/> + /// </summary> + public double PicogramsPerMilliliter => As(MassConcentrationUnit.PicogramPerMilliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PoundPerCubicFoot"/> + /// </summary> + public double PoundsPerCubicFoot => As(MassConcentrationUnit.PoundPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PoundPerCubicInch"/> + /// </summary> + public double PoundsPerCubicInch => As(MassConcentrationUnit.PoundPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PoundPerImperialGallon"/> + /// </summary> + public double PoundsPerImperialGallon => As(MassConcentrationUnit.PoundPerImperialGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.PoundPerUSGallon"/> + /// </summary> + public double PoundsPerUSGallon => As(MassConcentrationUnit.PoundPerUSGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.SlugPerCubicFoot"/> + /// </summary> + public double SlugsPerCubicFoot => As(MassConcentrationUnit.SlugPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.TonnePerCubicCentimeter"/> + /// </summary> + public double TonnesPerCubicCentimeter => As(MassConcentrationUnit.TonnePerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.TonnePerCubicMeter"/> + /// </summary> + public double TonnesPerCubicMeter => As(MassConcentrationUnit.TonnePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassConcentrationUnit.TonnePerCubicMillimeter"/> + /// </summary> + public double TonnesPerCubicMillimeter => As(MassConcentrationUnit.TonnePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MassConcentrationUnit -> BaseUnit + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.CentigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.CentigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.CentigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.CentigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.DecigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.DecigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.DecigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.DecigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.GramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilopoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilopoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MicrogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MicrogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MicrogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MicrogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MicrogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MilligramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MilligramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MilligramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MilligramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.MilligramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.NanogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.NanogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.NanogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.NanogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.OuncePerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.OuncePerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PicogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PicogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PicogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PicogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PoundPerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.PoundPerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.SlugPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.TonnePerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.TonnePerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.TonnePerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> MassConcentrationUnit + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicCentimeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicMillimeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicCentimeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMillimeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.KilopoundPerCubicFoot)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicInch, quantity => quantity.ToUnit(MassConcentrationUnit.KilopoundPerCubicInch)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerImperialGallon, quantity => quantity.ToUnit(MassConcentrationUnit.OuncePerImperialGallon)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerUSGallon, quantity => quantity.ToUnit(MassConcentrationUnit.OuncePerUSGallon)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerDeciliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerLiter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerMicroliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerMilliliter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerCubicFoot)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicInch, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerCubicInch)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerImperialGallon, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerImperialGallon)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerUSGallon, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerUSGallon)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.SlugPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.SlugPerCubicFoot)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicCentimeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicMeter)); + unitConverter.SetConversionFunction<MassConcentration>(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.CentigramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"cg/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.CentigramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"cg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.CentigramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"cg/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.CentigramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"cg/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.DecigramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"dg/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.DecigramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"dg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.DecigramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"dg/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.DecigramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"dg/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"g/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"g/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"г/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"g/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"g/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"g/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"g/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.GramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"g/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilogramPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kg/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilogramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kg/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilogramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кг/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilogramPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kg/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"kg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilopoundPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"kip/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.KilopoundPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"kip/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MicrogramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"µg/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MicrogramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"мкг/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MicrogramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"µg/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MicrogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"µg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MicrogramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"µg/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MicrogramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"µg/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MilligramPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"mg/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MilligramPerCubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"мг/м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MilligramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"mg/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MilligramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"mg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MilligramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"mg/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.MilligramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"mg/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.NanogramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"ng/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.NanogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"ng/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.NanogramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"ng/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.NanogramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"ng/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.OuncePerImperialGallon, new CultureInfo("en-US"), false, true, new string[]{"oz/gal (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.OuncePerUSGallon, new CultureInfo("en-US"), false, true, new string[]{"oz/gal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PicogramPerDeciliter, new CultureInfo("en-US"), false, true, new string[]{"pg/dL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PicogramPerLiter, new CultureInfo("en-US"), false, true, new string[]{"pg/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PicogramPerMicroliter, new CultureInfo("en-US"), false, true, new string[]{"pg/μL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PicogramPerMilliliter, new CultureInfo("en-US"), false, true, new string[]{"pg/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PoundPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"lb/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PoundPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"lb/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PoundPerImperialGallon, new CultureInfo("en-US"), false, true, new string[]{"ppg (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.PoundPerUSGallon, new CultureInfo("en-US"), false, true, new string[]{"ppg (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.SlugPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"slug/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.TonnePerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"t/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.TonnePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"t/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassConcentrationUnit.TonnePerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"t/mm³"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MassConcentrationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MassConcentrationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.CentigramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromCentigramsPerDeciliter(QuantityValue centigramsperdeciliter) + { + double value = (double) centigramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.CentigramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.CentigramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromCentigramsPerLiter(QuantityValue centigramsperliter) + { + double value = (double) centigramsperliter; + return new MassConcentration(value, MassConcentrationUnit.CentigramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.CentigramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromCentigramsPerMicroliter(QuantityValue centigramspermicroliter) + { + double value = (double) centigramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.CentigramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.CentigramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) + { + double value = (double) centigramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.CentigramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.DecigramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromDecigramsPerDeciliter(QuantityValue decigramsperdeciliter) + { + double value = (double) decigramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.DecigramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.DecigramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromDecigramsPerLiter(QuantityValue decigramsperliter) + { + double value = (double) decigramsperliter; + return new MassConcentration(value, MassConcentrationUnit.DecigramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.DecigramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromDecigramsPerMicroliter(QuantityValue decigramspermicroliter) + { + double value = (double) decigramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.DecigramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.DecigramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) + { + double value = (double) decigramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.DecigramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) + { + double value = (double) gramspercubiccentimeter; + return new MassConcentration(value, MassConcentrationUnit.GramPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) + { + double value = (double) gramspercubicmeter; + return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) + { + double value = (double) gramspercubicmillimeter; + return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerDeciliter(QuantityValue gramsperdeciliter) + { + double value = (double) gramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.GramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerLiter(QuantityValue gramsperliter) + { + double value = (double) gramsperliter; + return new MassConcentration(value, MassConcentrationUnit.GramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerMicroliter(QuantityValue gramspermicroliter) + { + double value = (double) gramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.GramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.GramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromGramsPerMilliliter(QuantityValue gramspermilliliter) + { + double value = (double) gramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.GramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.KilogramPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) + { + double value = (double) kilogramspercubiccentimeter; + return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.KilogramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) + { + double value = (double) kilogramspercubicmeter; + return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.KilogramPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) + { + double value = (double) kilogramspercubicmillimeter; + return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.KilogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromKilogramsPerLiter(QuantityValue kilogramsperliter) + { + double value = (double) kilogramsperliter; + return new MassConcentration(value, MassConcentrationUnit.KilogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.KilopoundPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) + { + double value = (double) kilopoundspercubicfoot; + return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.KilopoundPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) + { + double value = (double) kilopoundspercubicinch; + return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MicrogramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMicrogramsPerCubicMeter(QuantityValue microgramspercubicmeter) + { + double value = (double) microgramspercubicmeter; + return new MassConcentration(value, MassConcentrationUnit.MicrogramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MicrogramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMicrogramsPerDeciliter(QuantityValue microgramsperdeciliter) + { + double value = (double) microgramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.MicrogramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MicrogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMicrogramsPerLiter(QuantityValue microgramsperliter) + { + double value = (double) microgramsperliter; + return new MassConcentration(value, MassConcentrationUnit.MicrogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MicrogramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMicrogramsPerMicroliter(QuantityValue microgramspermicroliter) + { + double value = (double) microgramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MicrogramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) + { + double value = (double) microgramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MilligramPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) + { + double value = (double) milligramspercubicmeter; + return new MassConcentration(value, MassConcentrationUnit.MilligramPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MilligramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMilligramsPerDeciliter(QuantityValue milligramsperdeciliter) + { + double value = (double) milligramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.MilligramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MilligramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMilligramsPerLiter(QuantityValue milligramsperliter) + { + double value = (double) milligramsperliter; + return new MassConcentration(value, MassConcentrationUnit.MilligramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MilligramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMilligramsPerMicroliter(QuantityValue milligramspermicroliter) + { + double value = (double) milligramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.MilligramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.MilligramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) + { + double value = (double) milligramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.MilligramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.NanogramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromNanogramsPerDeciliter(QuantityValue nanogramsperdeciliter) + { + double value = (double) nanogramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.NanogramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.NanogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromNanogramsPerLiter(QuantityValue nanogramsperliter) + { + double value = (double) nanogramsperliter; + return new MassConcentration(value, MassConcentrationUnit.NanogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.NanogramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromNanogramsPerMicroliter(QuantityValue nanogramspermicroliter) + { + double value = (double) nanogramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.NanogramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.NanogramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) + { + double value = (double) nanogramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.NanogramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.OuncePerImperialGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromOuncesPerImperialGallon(QuantityValue ouncesperimperialgallon) + { + double value = (double) ouncesperimperialgallon; + return new MassConcentration(value, MassConcentrationUnit.OuncePerImperialGallon); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.OuncePerUSGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromOuncesPerUSGallon(QuantityValue ouncesperusgallon) + { + double value = (double) ouncesperusgallon; + return new MassConcentration(value, MassConcentrationUnit.OuncePerUSGallon); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PicogramPerDeciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPicogramsPerDeciliter(QuantityValue picogramsperdeciliter) + { + double value = (double) picogramsperdeciliter; + return new MassConcentration(value, MassConcentrationUnit.PicogramPerDeciliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PicogramPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPicogramsPerLiter(QuantityValue picogramsperliter) + { + double value = (double) picogramsperliter; + return new MassConcentration(value, MassConcentrationUnit.PicogramPerLiter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PicogramPerMicroliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPicogramsPerMicroliter(QuantityValue picogramspermicroliter) + { + double value = (double) picogramspermicroliter; + return new MassConcentration(value, MassConcentrationUnit.PicogramPerMicroliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PicogramPerMilliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) + { + double value = (double) picogramspermilliliter; + return new MassConcentration(value, MassConcentrationUnit.PicogramPerMilliliter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PoundPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) + { + double value = (double) poundspercubicfoot; + return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PoundPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPoundsPerCubicInch(QuantityValue poundspercubicinch) + { + double value = (double) poundspercubicinch; + return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PoundPerImperialGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) + { + double value = (double) poundsperimperialgallon; + return new MassConcentration(value, MassConcentrationUnit.PoundPerImperialGallon); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.PoundPerUSGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromPoundsPerUSGallon(QuantityValue poundsperusgallon) + { + double value = (double) poundsperusgallon; + return new MassConcentration(value, MassConcentrationUnit.PoundPerUSGallon); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.SlugPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) + { + double value = (double) slugspercubicfoot; + return new MassConcentration(value, MassConcentrationUnit.SlugPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.TonnePerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) + { + double value = (double) tonnespercubiccentimeter; + return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.TonnePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) + { + double value = (double) tonnespercubicmeter; + return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="MassConcentration"/> from <see cref="MassConcentrationUnit.TonnePerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassConcentration FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) + { + double value = (double) tonnespercubicmillimeter; + return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MassConcentrationUnit" /> to <see cref="MassConcentration" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MassConcentration unit value.</returns> + public static MassConcentration From(QuantityValue value, MassConcentrationUnit fromUnit) + { + return new MassConcentration((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MassConcentration Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MassConcentration Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MassConcentration, MassConcentrationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MassConcentration result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MassConcentration result) + { + return QuantityParser.Default.TryParse<MassConcentration, MassConcentrationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassConcentrationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassConcentrationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MassConcentrationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MassConcentrationUnit)"/> + public static bool TryParseUnit(string str, out MassConcentrationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MassConcentrationUnit unit) + { + return UnitParser.Default.TryParse<MassConcentrationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MassConcentration operator -(MassConcentration right) + { + return new MassConcentration(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassConcentration"/> from adding two <see cref="MassConcentration"/>.</summary> + public static MassConcentration operator +(MassConcentration left, MassConcentration right) + { + return new MassConcentration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassConcentration"/> from subtracting two <see cref="MassConcentration"/>.</summary> + public static MassConcentration operator -(MassConcentration left, MassConcentration right) + { + return new MassConcentration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassConcentration"/> from multiplying value and <see cref="MassConcentration"/>.</summary> + public static MassConcentration operator *(double left, MassConcentration right) + { + return new MassConcentration(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassConcentration"/> from multiplying value and <see cref="MassConcentration"/>.</summary> + public static MassConcentration operator *(MassConcentration left, double right) + { + return new MassConcentration(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MassConcentration"/> from dividing <see cref="MassConcentration"/> by value.</summary> + public static MassConcentration operator /(MassConcentration left, double right) + { + return new MassConcentration(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MassConcentration"/> by <see cref="MassConcentration"/>.</summary> + public static double operator /(MassConcentration left, MassConcentration right) + { + return left.KilogramsPerCubicMeter / right.KilogramsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MassConcentration left, MassConcentration right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MassConcentration left, MassConcentration right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MassConcentration left, MassConcentration right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MassConcentration left, MassConcentration right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MassConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MassConcentration left, MassConcentration right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MassConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MassConcentration left, MassConcentration right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MassConcentration otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MassConcentration other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MassConcentration"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MassConcentration otherQuantity)) throw new ArgumentException("Expected type MassConcentration.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MassConcentration"/> with another <see cref="MassConcentration"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MassConcentration other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MassConcentration within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(MassConcentration other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MassConcentration.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MassConcentrationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MassConcentrationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MassConcentration to another MassConcentration with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MassConcentration with the specified unit.</returns> + public MassConcentration ToUnit(MassConcentrationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MassConcentration"/> to another <see cref="MassConcentration"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MassConcentration with the specified unit.</returns> + public MassConcentration ToUnit(MassConcentrationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MassConcentration), Unit, typeof(MassConcentration), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MassConcentration)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MassConcentration"/> to another <see cref="MassConcentration"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MassConcentration"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MassConcentrationUnit unit, [NotNullWhen(true)] out MassConcentration? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MassConcentration? convertedOrNull = (Unit, unit) switch + { + // MassConcentrationUnit -> BaseUnit + (MassConcentrationUnit.CentigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.CentigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.CentigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.CentigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.DecigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.DecigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.DecigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.DecigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-3, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e3, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-6, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-1, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-6, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.GramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-3, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.KilogramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.KilogramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.KilogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.KilopoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 0.062427961) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.KilopoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 3.6127298147753e-5) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MicrogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e3) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MicrogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MicrogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MicrogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MicrogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MilligramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e3) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MilligramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MilligramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MilligramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.MilligramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.NanogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.NanogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.NanogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.NanogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.OuncePerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration( _value / 0.1603586720609, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.OuncePerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration( _value / 0.1335264711843, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PicogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PicogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PicogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PicogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 0.062427961, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 3.6127298147753e-5, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PoundPerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 9.9776398e1, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.PoundPerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 1.19826427e2, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.SlugPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 515.378818, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.TonnePerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-9, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.TonnePerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 0.001, MassConcentrationUnit.KilogramPerCubicMeter), + (MassConcentrationUnit.TonnePerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-12, MassConcentrationUnit.KilogramPerCubicMeter), + + // BaseUnit -> MassConcentrationUnit + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-2d, MassConcentrationUnit.CentigramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerLiter) => new MassConcentration((_value) / 1e-2d, MassConcentrationUnit.CentigramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-2d, MassConcentrationUnit.CentigramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-2d, MassConcentrationUnit.CentigramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-1d, MassConcentrationUnit.DecigramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerLiter) => new MassConcentration((_value) / 1e-1d, MassConcentrationUnit.DecigramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-1d, MassConcentrationUnit.DecigramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-1d, MassConcentrationUnit.DecigramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicCentimeter) => new MassConcentration(_value * 1e-3, MassConcentrationUnit.GramPerCubicCentimeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMeter) => new MassConcentration(_value * 1e3, MassConcentrationUnit.GramPerCubicMeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMillimeter) => new MassConcentration(_value * 1e-6, MassConcentrationUnit.GramPerCubicMillimeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerDeciliter) => new MassConcentration(_value * 1e-1, MassConcentrationUnit.GramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerLiter) => new MassConcentration(_value, MassConcentrationUnit.GramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMicroliter) => new MassConcentration(_value * 1e-6, MassConcentrationUnit.GramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMilliliter) => new MassConcentration(_value * 1e-3, MassConcentrationUnit.GramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicCentimeter) => new MassConcentration((_value * 1e-3) / 1e3d, MassConcentrationUnit.KilogramPerCubicCentimeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMillimeter) => new MassConcentration((_value * 1e-6) / 1e3d, MassConcentrationUnit.KilogramPerCubicMillimeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerLiter) => new MassConcentration((_value) / 1e3d, MassConcentrationUnit.KilogramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicFoot) => new MassConcentration((_value * 0.062427961) / 1e3d, MassConcentrationUnit.KilopoundPerCubicFoot), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicInch) => new MassConcentration((_value * 3.6127298147753e-5) / 1e3d, MassConcentrationUnit.KilopoundPerCubicInch), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerCubicMeter) => new MassConcentration((_value * 1e3) / 1e-6d, MassConcentrationUnit.MicrogramPerCubicMeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-6d, MassConcentrationUnit.MicrogramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerLiter) => new MassConcentration((_value) / 1e-6d, MassConcentrationUnit.MicrogramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-6d, MassConcentrationUnit.MicrogramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-6d, MassConcentrationUnit.MicrogramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerCubicMeter) => new MassConcentration((_value * 1e3) / 1e-3d, MassConcentrationUnit.MilligramPerCubicMeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-3d, MassConcentrationUnit.MilligramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerLiter) => new MassConcentration((_value) / 1e-3d, MassConcentrationUnit.MilligramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-3d, MassConcentrationUnit.MilligramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-3d, MassConcentrationUnit.MilligramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-9d, MassConcentrationUnit.NanogramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerLiter) => new MassConcentration((_value) / 1e-9d, MassConcentrationUnit.NanogramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-9d, MassConcentrationUnit.NanogramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-9d, MassConcentrationUnit.NanogramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerImperialGallon) => new MassConcentration(_value * 0.1603586720609, MassConcentrationUnit.OuncePerImperialGallon), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerUSGallon) => new MassConcentration(_value * 0.1335264711843, MassConcentrationUnit.OuncePerUSGallon), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-12d, MassConcentrationUnit.PicogramPerDeciliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerLiter) => new MassConcentration((_value) / 1e-12d, MassConcentrationUnit.PicogramPerLiter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-12d, MassConcentrationUnit.PicogramPerMicroliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-12d, MassConcentrationUnit.PicogramPerMilliliter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicFoot) => new MassConcentration(_value * 0.062427961, MassConcentrationUnit.PoundPerCubicFoot), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicInch) => new MassConcentration(_value * 3.6127298147753e-5, MassConcentrationUnit.PoundPerCubicInch), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerImperialGallon) => new MassConcentration(_value / 9.9776398e1, MassConcentrationUnit.PoundPerImperialGallon), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerUSGallon) => new MassConcentration(_value / 1.19826427e2, MassConcentrationUnit.PoundPerUSGallon), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.SlugPerCubicFoot) => new MassConcentration(_value * 0.00194032033, MassConcentrationUnit.SlugPerCubicFoot), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicCentimeter) => new MassConcentration(_value * 1e-9, MassConcentrationUnit.TonnePerCubicCentimeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMeter) => new MassConcentration(_value * 0.001, MassConcentrationUnit.TonnePerCubicMeter), + (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMillimeter) => new MassConcentration(_value * 1e-12, MassConcentrationUnit.TonnePerCubicMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MassConcentrationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MassConcentrationUnit> IQuantity<MassConcentrationUnit>.ToUnit(MassConcentrationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MassConcentrationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassConcentration)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassConcentration)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassConcentration)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MassConcentration)) + return this; + else if (conversionType == typeof(MassConcentrationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MassConcentration.Info; + else if (conversionType == typeof(BaseDimensions)) + return MassConcentration.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MassConcentration)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentrationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentrationUnit.g.cs new file mode 100644 index 0000000000..e80ca6a945 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassConcentration/MassConcentrationUnit.g.cs @@ -0,0 +1,80 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MassConcentrationUnit + { + CentigramPerDeciliter = 1, + CentigramPerLiter = 2, + CentigramPerMicroliter = 3, + CentigramPerMilliliter = 4, + DecigramPerDeciliter = 5, + DecigramPerLiter = 6, + DecigramPerMicroliter = 7, + DecigramPerMilliliter = 8, + GramPerCubicCentimeter = 9, + GramPerCubicMeter = 10, + GramPerCubicMillimeter = 11, + GramPerDeciliter = 12, + GramPerLiter = 13, + GramPerMicroliter = 14, + GramPerMilliliter = 15, + KilogramPerCubicCentimeter = 16, + KilogramPerCubicMeter = 17, + KilogramPerCubicMillimeter = 18, + KilogramPerLiter = 19, + KilopoundPerCubicFoot = 20, + KilopoundPerCubicInch = 21, + MicrogramPerCubicMeter = 22, + MicrogramPerDeciliter = 23, + MicrogramPerLiter = 24, + MicrogramPerMicroliter = 25, + MicrogramPerMilliliter = 26, + MilligramPerCubicMeter = 27, + MilligramPerDeciliter = 28, + MilligramPerLiter = 29, + MilligramPerMicroliter = 30, + MilligramPerMilliliter = 31, + NanogramPerDeciliter = 32, + NanogramPerLiter = 33, + NanogramPerMicroliter = 34, + NanogramPerMilliliter = 35, + OuncePerImperialGallon = 36, + OuncePerUSGallon = 37, + PicogramPerDeciliter = 38, + PicogramPerLiter = 39, + PicogramPerMicroliter = 40, + PicogramPerMilliliter = 41, + PoundPerCubicFoot = 42, + PoundPerCubicInch = 43, + PoundPerImperialGallon = 44, + PoundPerUSGallon = 45, + SlugPerCubicFoot = 46, + TonnePerCubicCentimeter = 47, + TonnePerCubicMeter = 48, + TonnePerCubicMillimeter = 49, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlow.csproj b/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlow.csproj new file mode 100644 index 0000000000..81196f6dc2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlow.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MassFlow</Title> + <Description>Adds MassFlow units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>massflow unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{a0821347-be46-c587-b61d-5152c578048d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MassFlow</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlow.g.cs b/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlow.g.cs new file mode 100644 index 0000000000..0bc06d5905 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlow.g.cs @@ -0,0 +1,1512 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time). + /// </summary> + [DataContract] + public readonly partial struct MassFlow : IArithmeticQuantity<MassFlow, MassFlowUnit, double>, IEquatable<MassFlow>, IComparable, IComparable<MassFlow>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MassFlowUnit? _unit; + + static MassFlow() + { + BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); + BaseUnit = MassFlowUnit.GramPerSecond; + Units = Enum.GetValues(typeof(MassFlowUnit)).Cast<MassFlowUnit>().ToArray(); + Zero = new MassFlow(0, BaseUnit); + Info = new QuantityInfo<MassFlowUnit>("MassFlow", + new UnitInfo<MassFlowUnit>[] + { + new UnitInfo<MassFlowUnit>(MassFlowUnit.CentigramPerDay, "CentigramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.CentigramPerSecond, "CentigramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.DecagramPerDay, "DecagramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.DecagramPerSecond, "DecagramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.DecigramPerDay, "DecigramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.DecigramPerSecond, "DecigramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.GramPerDay, "GramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.GramPerHour, "GramsPerHour", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.GramPerSecond, "GramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.HectogramPerDay, "HectogramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.HectogramPerSecond, "HectogramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.KilogramPerDay, "KilogramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.KilogramPerHour, "KilogramsPerHour", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.KilogramPerMinute, "KilogramsPerMinute", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.KilogramPerSecond, "KilogramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MegagramPerDay, "MegagramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MegapoundPerDay, "MegapoundsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MegapoundPerHour, "MegapoundsPerHour", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MegapoundPerMinute, "MegapoundsPerMinute", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MegapoundPerSecond, "MegapoundsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MicrogramPerDay, "MicrogramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MicrogramPerSecond, "MicrogramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MilligramPerDay, "MilligramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.MilligramPerSecond, "MilligramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.NanogramPerDay, "NanogramsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.NanogramPerSecond, "NanogramsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.PoundPerDay, "PoundsPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.PoundPerHour, "PoundsPerHour", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.PoundPerMinute, "PoundsPerMinute", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.PoundPerSecond, "PoundsPerSecond", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.ShortTonPerHour, "ShortTonsPerHour", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.TonnePerDay, "TonnesPerDay", BaseUnits.Undefined), + new UnitInfo<MassFlowUnit>(MassFlowUnit.TonnePerHour, "TonnesPerHour", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MassFlow(double value, MassFlowUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MassFlow" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MassFlowUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. + /// </summary> + public static MassFlowUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MassFlow quantity. + /// </summary> + public static MassFlowUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. + /// </summary> + public static MassFlow Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MassFlow AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MassFlowUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MassFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.CentigramPerDay"/> + /// </summary> + public double CentigramsPerDay => As(MassFlowUnit.CentigramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.CentigramPerSecond"/> + /// </summary> + public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.DecagramPerDay"/> + /// </summary> + public double DecagramsPerDay => As(MassFlowUnit.DecagramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.DecagramPerSecond"/> + /// </summary> + public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.DecigramPerDay"/> + /// </summary> + public double DecigramsPerDay => As(MassFlowUnit.DecigramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.DecigramPerSecond"/> + /// </summary> + public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.GramPerDay"/> + /// </summary> + public double GramsPerDay => As(MassFlowUnit.GramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.GramPerHour"/> + /// </summary> + public double GramsPerHour => As(MassFlowUnit.GramPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.GramPerSecond"/> + /// </summary> + public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.HectogramPerDay"/> + /// </summary> + public double HectogramsPerDay => As(MassFlowUnit.HectogramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.HectogramPerSecond"/> + /// </summary> + public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.KilogramPerDay"/> + /// </summary> + public double KilogramsPerDay => As(MassFlowUnit.KilogramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.KilogramPerHour"/> + /// </summary> + public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.KilogramPerMinute"/> + /// </summary> + public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.KilogramPerSecond"/> + /// </summary> + public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MegagramPerDay"/> + /// </summary> + public double MegagramsPerDay => As(MassFlowUnit.MegagramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MegapoundPerDay"/> + /// </summary> + public double MegapoundsPerDay => As(MassFlowUnit.MegapoundPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MegapoundPerHour"/> + /// </summary> + public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MegapoundPerMinute"/> + /// </summary> + public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MegapoundPerSecond"/> + /// </summary> + public double MegapoundsPerSecond => As(MassFlowUnit.MegapoundPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MicrogramPerDay"/> + /// </summary> + public double MicrogramsPerDay => As(MassFlowUnit.MicrogramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MicrogramPerSecond"/> + /// </summary> + public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MilligramPerDay"/> + /// </summary> + public double MilligramsPerDay => As(MassFlowUnit.MilligramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.MilligramPerSecond"/> + /// </summary> + public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.NanogramPerDay"/> + /// </summary> + public double NanogramsPerDay => As(MassFlowUnit.NanogramPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.NanogramPerSecond"/> + /// </summary> + public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.PoundPerDay"/> + /// </summary> + public double PoundsPerDay => As(MassFlowUnit.PoundPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.PoundPerHour"/> + /// </summary> + public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.PoundPerMinute"/> + /// </summary> + public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.PoundPerSecond"/> + /// </summary> + public double PoundsPerSecond => As(MassFlowUnit.PoundPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.ShortTonPerHour"/> + /// </summary> + public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.TonnePerDay"/> + /// </summary> + public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFlowUnit.TonnePerHour"/> + /// </summary> + public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MassFlowUnit -> BaseUnit + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.CentigramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.CentigramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.DecagramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.DecagramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.DecigramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.DecigramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.HectogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.HectogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.KilogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.KilogramPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.KilogramPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.KilogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MegagramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MegapoundPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MegapoundPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MegapoundPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MegapoundPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MicrogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MicrogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MilligramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.MilligramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.NanogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.NanogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.PoundPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.PoundPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.PoundPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.PoundPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.ShortTonPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.TonnePerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.TonnePerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> MassFlowUnit + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerDay, quantity => quantity.ToUnit(MassFlowUnit.CentigramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.CentigramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerDay, quantity => quantity.ToUnit(MassFlowUnit.DecagramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.DecagramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerDay, quantity => quantity.ToUnit(MassFlowUnit.DecigramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.DecigramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerDay, quantity => quantity.ToUnit(MassFlowUnit.GramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerHour, quantity => quantity.ToUnit(MassFlowUnit.GramPerHour)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.HectogramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.HectogramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerHour, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerHour)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerMinute, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerMinute)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MegagramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MegagramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerDay, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerHour, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerHour)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerMinute, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerMinute)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MicrogramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MicrogramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MilligramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MilligramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.NanogramPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.NanogramPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerDay, quantity => quantity.ToUnit(MassFlowUnit.PoundPerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerHour, quantity => quantity.ToUnit(MassFlowUnit.PoundPerHour)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerMinute, quantity => quantity.ToUnit(MassFlowUnit.PoundPerMinute)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerSecond, quantity => quantity.ToUnit(MassFlowUnit.PoundPerSecond)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.ShortTonPerHour, quantity => quantity.ToUnit(MassFlowUnit.ShortTonPerHour)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerDay, quantity => quantity.ToUnit(MassFlowUnit.TonnePerDay)); + unitConverter.SetConversionFunction<MassFlow>(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerHour, quantity => quantity.ToUnit(MassFlowUnit.TonnePerHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.CentigramPerDay, new CultureInfo("en-US"), false, true, new string[]{"cg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.CentigramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"cg/s", "cg/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.DecagramPerDay, new CultureInfo("en-US"), false, true, new string[]{"dag/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.DecagramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"dag/s", "dag/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.DecigramPerDay, new CultureInfo("en-US"), false, true, new string[]{"dg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.DecigramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"dg/s", "dg/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.GramPerDay, new CultureInfo("en-US"), false, true, new string[]{"g/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.GramPerHour, new CultureInfo("en-US"), false, true, new string[]{"g/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.GramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"g/s", "g/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.HectogramPerDay, new CultureInfo("en-US"), false, true, new string[]{"hg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.HectogramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"hg/s", "hg/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.KilogramPerDay, new CultureInfo("en-US"), false, true, new string[]{"kg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.KilogramPerHour, new CultureInfo("en-US"), false, true, new string[]{"kg/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.KilogramPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"кг/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.KilogramPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kg/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.KilogramPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"кг/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.KilogramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kg/s", "kg/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MegagramPerDay, new CultureInfo("en-US"), false, true, new string[]{"Mg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MegapoundPerDay, new CultureInfo("en-US"), false, true, new string[]{"Mlb/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MegapoundPerHour, new CultureInfo("en-US"), false, true, new string[]{"Mlb/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MegapoundPerMinute, new CultureInfo("en-US"), false, true, new string[]{"Mlb/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MegapoundPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Mlb/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MicrogramPerDay, new CultureInfo("en-US"), false, true, new string[]{"µg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MicrogramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µg/s", "µg/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MilligramPerDay, new CultureInfo("en-US"), false, true, new string[]{"mg/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.MilligramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mg/s", "mg/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.NanogramPerDay, new CultureInfo("en-US"), false, true, new string[]{"ng/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.NanogramPerSecond, new CultureInfo("en-US"), false, true, new string[]{"ng/s", "ng/S"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.PoundPerDay, new CultureInfo("en-US"), false, true, new string[]{"lb/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.PoundPerHour, new CultureInfo("en-US"), false, true, new string[]{"lb/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.PoundPerMinute, new CultureInfo("en-US"), false, true, new string[]{"lb/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.PoundPerSecond, new CultureInfo("en-US"), false, true, new string[]{"lb/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.ShortTonPerHour, new CultureInfo("en-US"), false, true, new string[]{"short tn/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.TonnePerDay, new CultureInfo("en-US"), false, true, new string[]{"t/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFlowUnit.TonnePerHour, new CultureInfo("en-US"), false, true, new string[]{"t/h"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MassFlowUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MassFlowUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.CentigramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromCentigramsPerDay(QuantityValue centigramsperday) + { + double value = (double) centigramsperday; + return new MassFlow(value, MassFlowUnit.CentigramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.CentigramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) + { + double value = (double) centigramspersecond; + return new MassFlow(value, MassFlowUnit.CentigramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.DecagramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromDecagramsPerDay(QuantityValue decagramsperday) + { + double value = (double) decagramsperday; + return new MassFlow(value, MassFlowUnit.DecagramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.DecagramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) + { + double value = (double) decagramspersecond; + return new MassFlow(value, MassFlowUnit.DecagramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.DecigramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromDecigramsPerDay(QuantityValue decigramsperday) + { + double value = (double) decigramsperday; + return new MassFlow(value, MassFlowUnit.DecigramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.DecigramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) + { + double value = (double) decigramspersecond; + return new MassFlow(value, MassFlowUnit.DecigramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.GramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromGramsPerDay(QuantityValue gramsperday) + { + double value = (double) gramsperday; + return new MassFlow(value, MassFlowUnit.GramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.GramPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromGramsPerHour(QuantityValue gramsperhour) + { + double value = (double) gramsperhour; + return new MassFlow(value, MassFlowUnit.GramPerHour); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.GramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) + { + double value = (double) gramspersecond; + return new MassFlow(value, MassFlowUnit.GramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.HectogramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromHectogramsPerDay(QuantityValue hectogramsperday) + { + double value = (double) hectogramsperday; + return new MassFlow(value, MassFlowUnit.HectogramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.HectogramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) + { + double value = (double) hectogramspersecond; + return new MassFlow(value, MassFlowUnit.HectogramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.KilogramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromKilogramsPerDay(QuantityValue kilogramsperday) + { + double value = (double) kilogramsperday; + return new MassFlow(value, MassFlowUnit.KilogramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.KilogramPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) + { + double value = (double) kilogramsperhour; + return new MassFlow(value, MassFlowUnit.KilogramPerHour); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.KilogramPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromKilogramsPerMinute(QuantityValue kilogramsperminute) + { + double value = (double) kilogramsperminute; + return new MassFlow(value, MassFlowUnit.KilogramPerMinute); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.KilogramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) + { + double value = (double) kilogramspersecond; + return new MassFlow(value, MassFlowUnit.KilogramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MegagramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMegagramsPerDay(QuantityValue megagramsperday) + { + double value = (double) megagramsperday; + return new MassFlow(value, MassFlowUnit.MegagramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MegapoundPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMegapoundsPerDay(QuantityValue megapoundsperday) + { + double value = (double) megapoundsperday; + return new MassFlow(value, MassFlowUnit.MegapoundPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MegapoundPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) + { + double value = (double) megapoundsperhour; + return new MassFlow(value, MassFlowUnit.MegapoundPerHour); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MegapoundPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMegapoundsPerMinute(QuantityValue megapoundsperminute) + { + double value = (double) megapoundsperminute; + return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MegapoundPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMegapoundsPerSecond(QuantityValue megapoundspersecond) + { + double value = (double) megapoundspersecond; + return new MassFlow(value, MassFlowUnit.MegapoundPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MicrogramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMicrogramsPerDay(QuantityValue microgramsperday) + { + double value = (double) microgramsperday; + return new MassFlow(value, MassFlowUnit.MicrogramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MicrogramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) + { + double value = (double) microgramspersecond; + return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MilligramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMilligramsPerDay(QuantityValue milligramsperday) + { + double value = (double) milligramsperday; + return new MassFlow(value, MassFlowUnit.MilligramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.MilligramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) + { + double value = (double) milligramspersecond; + return new MassFlow(value, MassFlowUnit.MilligramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.NanogramPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromNanogramsPerDay(QuantityValue nanogramsperday) + { + double value = (double) nanogramsperday; + return new MassFlow(value, MassFlowUnit.NanogramPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.NanogramPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) + { + double value = (double) nanogramspersecond; + return new MassFlow(value, MassFlowUnit.NanogramPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.PoundPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromPoundsPerDay(QuantityValue poundsperday) + { + double value = (double) poundsperday; + return new MassFlow(value, MassFlowUnit.PoundPerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.PoundPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) + { + double value = (double) poundsperhour; + return new MassFlow(value, MassFlowUnit.PoundPerHour); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.PoundPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromPoundsPerMinute(QuantityValue poundsperminute) + { + double value = (double) poundsperminute; + return new MassFlow(value, MassFlowUnit.PoundPerMinute); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.PoundPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromPoundsPerSecond(QuantityValue poundspersecond) + { + double value = (double) poundspersecond; + return new MassFlow(value, MassFlowUnit.PoundPerSecond); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.ShortTonPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) + { + double value = (double) shorttonsperhour; + return new MassFlow(value, MassFlowUnit.ShortTonPerHour); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.TonnePerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) + { + double value = (double) tonnesperday; + return new MassFlow(value, MassFlowUnit.TonnePerDay); + } + + /// <summary> + /// Creates a <see cref="MassFlow"/> from <see cref="MassFlowUnit.TonnePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) + { + double value = (double) tonnesperhour; + return new MassFlow(value, MassFlowUnit.TonnePerHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MassFlowUnit" /> to <see cref="MassFlow" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MassFlow unit value.</returns> + public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) + { + return new MassFlow((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MassFlow Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MassFlow Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MassFlow, MassFlowUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MassFlow result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MassFlow result) + { + return QuantityParser.Default.TryParse<MassFlow, MassFlowUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassFlowUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassFlowUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MassFlowUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MassFlowUnit)"/> + public static bool TryParseUnit(string str, out MassFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MassFlowUnit unit) + { + return UnitParser.Default.TryParse<MassFlowUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MassFlow operator -(MassFlow right) + { + return new MassFlow(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassFlow"/> from adding two <see cref="MassFlow"/>.</summary> + public static MassFlow operator +(MassFlow left, MassFlow right) + { + return new MassFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassFlow"/> from subtracting two <see cref="MassFlow"/>.</summary> + public static MassFlow operator -(MassFlow left, MassFlow right) + { + return new MassFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassFlow"/> from multiplying value and <see cref="MassFlow"/>.</summary> + public static MassFlow operator *(double left, MassFlow right) + { + return new MassFlow(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassFlow"/> from multiplying value and <see cref="MassFlow"/>.</summary> + public static MassFlow operator *(MassFlow left, double right) + { + return new MassFlow(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MassFlow"/> from dividing <see cref="MassFlow"/> by value.</summary> + public static MassFlow operator /(MassFlow left, double right) + { + return new MassFlow(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MassFlow"/> by <see cref="MassFlow"/>.</summary> + public static double operator /(MassFlow left, MassFlow right) + { + return left.GramsPerSecond / right.GramsPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MassFlow left, MassFlow right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MassFlow left, MassFlow right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MassFlow left, MassFlow right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MassFlow left, MassFlow right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MassFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MassFlow left, MassFlow right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MassFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MassFlow left, MassFlow right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MassFlow otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MassFlow other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MassFlow"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MassFlow otherQuantity)) throw new ArgumentException("Expected type MassFlow.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MassFlow"/> with another <see cref="MassFlow"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MassFlow other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MassFlow within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MassFlow.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MassFlowUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MassFlowUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MassFlow to another MassFlow with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MassFlow with the specified unit.</returns> + public MassFlow ToUnit(MassFlowUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MassFlow"/> to another <see cref="MassFlow"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MassFlow with the specified unit.</returns> + public MassFlow ToUnit(MassFlowUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MassFlow), Unit, typeof(MassFlow), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MassFlow)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MassFlow"/> to another <see cref="MassFlow"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MassFlow"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MassFlowUnit unit, [NotNullWhen(true)] out MassFlow? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MassFlow? convertedOrNull = (Unit, unit) switch + { + // MassFlowUnit -> BaseUnit + (MassFlowUnit.CentigramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-2d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.CentigramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-2d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.DecagramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e1d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.DecagramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e1d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.DecigramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-1d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.DecigramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-1d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.GramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 86400, MassFlowUnit.GramPerSecond), + (MassFlowUnit.GramPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 3600, MassFlowUnit.GramPerSecond), + (MassFlowUnit.HectogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e2d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.HectogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e2d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.KilogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e3d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.KilogramPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 3.6, MassFlowUnit.GramPerSecond), + (MassFlowUnit.KilogramPerMinute, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 0.06, MassFlowUnit.GramPerSecond), + (MassFlowUnit.KilogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e3d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MegagramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MegapoundPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 190.47936) * 1e6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MegapoundPerHour, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 7.93664) * 1e6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MegapoundPerMinute, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 0.132277) * 1e6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MegapoundPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value * 453.59237) * 1e6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MicrogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MicrogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-6d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MilligramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-3d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.MilligramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-3d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.NanogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-9d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.NanogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-9d, MassFlowUnit.GramPerSecond), + (MassFlowUnit.PoundPerDay, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 190.47936, MassFlowUnit.GramPerSecond), + (MassFlowUnit.PoundPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 7.93664, MassFlowUnit.GramPerSecond), + (MassFlowUnit.PoundPerMinute, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 0.132277, MassFlowUnit.GramPerSecond), + (MassFlowUnit.PoundPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 453.59237, MassFlowUnit.GramPerSecond), + (MassFlowUnit.ShortTonPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 251.9957611, MassFlowUnit.GramPerSecond), + (MassFlowUnit.TonnePerDay, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 0.0864000, MassFlowUnit.GramPerSecond), + (MassFlowUnit.TonnePerHour, MassFlowUnit.GramPerSecond) => new MassFlow(1000 * _value / 3.6, MassFlowUnit.GramPerSecond), + + // BaseUnit -> MassFlowUnit + (MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerDay) => new MassFlow((_value * 86400) / 1e-2d, MassFlowUnit.CentigramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerSecond) => new MassFlow((_value) / 1e-2d, MassFlowUnit.CentigramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerDay) => new MassFlow((_value * 86400) / 1e1d, MassFlowUnit.DecagramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerSecond) => new MassFlow((_value) / 1e1d, MassFlowUnit.DecagramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerDay) => new MassFlow((_value * 86400) / 1e-1d, MassFlowUnit.DecigramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerSecond) => new MassFlow((_value) / 1e-1d, MassFlowUnit.DecigramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerDay) => new MassFlow(_value * 86400, MassFlowUnit.GramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerHour) => new MassFlow(_value * 3600, MassFlowUnit.GramPerHour), + (MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerDay) => new MassFlow((_value * 86400) / 1e2d, MassFlowUnit.HectogramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerSecond) => new MassFlow((_value) / 1e2d, MassFlowUnit.HectogramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerDay) => new MassFlow((_value * 86400) / 1e3d, MassFlowUnit.KilogramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerHour) => new MassFlow(_value * 3.6, MassFlowUnit.KilogramPerHour), + (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerMinute) => new MassFlow(_value * 0.06, MassFlowUnit.KilogramPerMinute), + (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerSecond) => new MassFlow((_value) / 1e3d, MassFlowUnit.KilogramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MegagramPerDay) => new MassFlow((_value * 86400) / 1e6d, MassFlowUnit.MegagramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerDay) => new MassFlow((_value * 190.47936) / 1e6d, MassFlowUnit.MegapoundPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerHour) => new MassFlow((_value * 7.93664) / 1e6d, MassFlowUnit.MegapoundPerHour), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerMinute) => new MassFlow((_value * 0.132277) / 1e6d, MassFlowUnit.MegapoundPerMinute), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerSecond) => new MassFlow((_value / 453.59237) / 1e6d, MassFlowUnit.MegapoundPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerDay) => new MassFlow((_value * 86400) / 1e-6d, MassFlowUnit.MicrogramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerSecond) => new MassFlow((_value) / 1e-6d, MassFlowUnit.MicrogramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerDay) => new MassFlow((_value * 86400) / 1e-3d, MassFlowUnit.MilligramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerSecond) => new MassFlow((_value) / 1e-3d, MassFlowUnit.MilligramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerDay) => new MassFlow((_value * 86400) / 1e-9d, MassFlowUnit.NanogramPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerSecond) => new MassFlow((_value) / 1e-9d, MassFlowUnit.NanogramPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerDay) => new MassFlow(_value * 190.47936, MassFlowUnit.PoundPerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerHour) => new MassFlow(_value * 7.93664, MassFlowUnit.PoundPerHour), + (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerMinute) => new MassFlow(_value * 0.132277, MassFlowUnit.PoundPerMinute), + (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerSecond) => new MassFlow(_value / 453.59237, MassFlowUnit.PoundPerSecond), + (MassFlowUnit.GramPerSecond, MassFlowUnit.ShortTonPerHour) => new MassFlow(_value / 251.9957611, MassFlowUnit.ShortTonPerHour), + (MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerDay) => new MassFlow(_value * 0.0864000, MassFlowUnit.TonnePerDay), + (MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerHour) => new MassFlow(_value * 3.6 / 1000, MassFlowUnit.TonnePerHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MassFlowUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MassFlowUnit> IQuantity<MassFlowUnit>.ToUnit(MassFlowUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MassFlowUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFlow)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFlow)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFlow)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MassFlow)) + return this; + else if (conversionType == typeof(MassFlowUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MassFlow.Info; + else if (conversionType == typeof(BaseDimensions)) + return MassFlow.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MassFlow)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlowUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlowUnit.g.cs new file mode 100644 index 0000000000..7df77cf7b5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFlow/MassFlowUnit.g.cs @@ -0,0 +1,64 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MassFlowUnit + { + CentigramPerDay = 1, + CentigramPerSecond = 2, + DecagramPerDay = 3, + DecagramPerSecond = 4, + DecigramPerDay = 5, + DecigramPerSecond = 6, + GramPerDay = 7, + GramPerHour = 8, + GramPerSecond = 9, + HectogramPerDay = 10, + HectogramPerSecond = 11, + KilogramPerDay = 12, + KilogramPerHour = 13, + KilogramPerMinute = 14, + KilogramPerSecond = 15, + MegagramPerDay = 16, + MegapoundPerDay = 17, + MegapoundPerHour = 18, + MegapoundPerMinute = 19, + MegapoundPerSecond = 20, + MicrogramPerDay = 21, + MicrogramPerSecond = 22, + MilligramPerDay = 23, + MilligramPerSecond = 24, + NanogramPerDay = 25, + NanogramPerSecond = 26, + PoundPerDay = 27, + PoundPerHour = 28, + PoundPerMinute = 29, + PoundPerSecond = 30, + ShortTonPerHour = 31, + TonnePerDay = 32, + TonnePerHour = 33, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MassFlux/MassFlux.csproj b/UnitsNet.Modular/GeneratedCode/MassFlux/MassFlux.csproj new file mode 100644 index 0000000000..b5eeb16c83 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFlux/MassFlux.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MassFlux</Title> + <Description>Adds MassFlux units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>massflux unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{15622f39-b4c5-7e66-57bc-31900b6065c8}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MassFlux</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MassFlux/MassFlux.g.cs b/UnitsNet.Modular/GeneratedCode/MassFlux/MassFlux.g.cs new file mode 100644 index 0000000000..dfc9b6e170 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFlux/MassFlux.g.cs @@ -0,0 +1,1069 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Mass flux is the mass flow rate per unit area. + /// </summary> + [DataContract] + public readonly partial struct MassFlux : IArithmeticQuantity<MassFlux, MassFluxUnit, double>, IEquatable<MassFlux>, IComparable, IComparable<MassFlux>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MassFluxUnit? _unit; + + static MassFlux() + { + BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); + BaseUnit = MassFluxUnit.KilogramPerSecondPerSquareMeter; + Units = Enum.GetValues(typeof(MassFluxUnit)).Cast<MassFluxUnit>().ToArray(); + Zero = new MassFlux(0, BaseUnit); + Info = new QuantityInfo<MassFluxUnit>("MassFlux", + new UnitInfo<MassFluxUnit>[] + { + new UnitInfo<MassFluxUnit>(MassFluxUnit.GramPerHourPerSquareCentimeter, "GramsPerHourPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.GramPerHourPerSquareMeter, "GramsPerHourPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.GramPerHourPerSquareMillimeter, "GramsPerHourPerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.GramPerSecondPerSquareCentimeter, "GramsPerSecondPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.GramPerSecondPerSquareMeter, "GramsPerSecondPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.GramPerSecondPerSquareMillimeter, "GramsPerSecondPerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.KilogramPerHourPerSquareCentimeter, "KilogramsPerHourPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.KilogramPerHourPerSquareMeter, "KilogramsPerHourPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.KilogramPerHourPerSquareMillimeter, "KilogramsPerHourPerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, "KilogramsPerSecondPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.KilogramPerSecondPerSquareMeter, "KilogramsPerSecondPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<MassFluxUnit>(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "KilogramsPerSecondPerSquareMillimeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MassFlux(double value, MassFluxUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MassFlux" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MassFluxUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. + /// </summary> + public static MassFluxUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MassFlux quantity. + /// </summary> + public static MassFluxUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. + /// </summary> + public static MassFlux Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MassFlux AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MassFluxUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MassFlux.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.GramPerHourPerSquareCentimeter"/> + /// </summary> + public double GramsPerHourPerSquareCentimeter => As(MassFluxUnit.GramPerHourPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.GramPerHourPerSquareMeter"/> + /// </summary> + public double GramsPerHourPerSquareMeter => As(MassFluxUnit.GramPerHourPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.GramPerHourPerSquareMillimeter"/> + /// </summary> + public double GramsPerHourPerSquareMillimeter => As(MassFluxUnit.GramPerHourPerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.GramPerSecondPerSquareCentimeter"/> + /// </summary> + public double GramsPerSecondPerSquareCentimeter => As(MassFluxUnit.GramPerSecondPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.GramPerSecondPerSquareMeter"/> + /// </summary> + public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.GramPerSecondPerSquareMillimeter"/> + /// </summary> + public double GramsPerSecondPerSquareMillimeter => As(MassFluxUnit.GramPerSecondPerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.KilogramPerHourPerSquareCentimeter"/> + /// </summary> + public double KilogramsPerHourPerSquareCentimeter => As(MassFluxUnit.KilogramPerHourPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.KilogramPerHourPerSquareMeter"/> + /// </summary> + public double KilogramsPerHourPerSquareMeter => As(MassFluxUnit.KilogramPerHourPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.KilogramPerHourPerSquareMillimeter"/> + /// </summary> + public double KilogramsPerHourPerSquareMillimeter => As(MassFluxUnit.KilogramPerHourPerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.KilogramPerSecondPerSquareCentimeter"/> + /// </summary> + public double KilogramsPerSecondPerSquareCentimeter => As(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.KilogramPerSecondPerSquareMeter"/> + /// </summary> + public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFluxUnit.KilogramPerSecondPerSquareMillimeter"/> + /// </summary> + public double KilogramsPerSecondPerSquareMillimeter => As(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MassFluxUnit -> BaseUnit + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.GramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.GramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.GramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.GramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.GramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.GramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> MassFluxUnit + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareCentimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareMillimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareCentimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareMillimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareCentimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMillimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareCentimeter)); + unitConverter.SetConversionFunction<MassFlux>(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.GramPerHourPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"g·h⁻¹·cm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.GramPerHourPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"g·h⁻¹·m⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.GramPerHourPerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"g·h⁻¹·mm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.GramPerSecondPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"g·s⁻¹·cm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.GramPerSecondPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"g·s⁻¹·m⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.GramPerSecondPerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"g·s⁻¹·mm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.KilogramPerHourPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·h⁻¹·cm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.KilogramPerHourPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kg·h⁻¹·m⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.KilogramPerHourPerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·h⁻¹·mm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·s⁻¹·cm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.KilogramPerSecondPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kg·s⁻¹·m⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·s⁻¹·mm⁻²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MassFluxUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MassFluxUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.GramPerHourPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromGramsPerHourPerSquareCentimeter(QuantityValue gramsperhourpersquarecentimeter) + { + double value = (double) gramsperhourpersquarecentimeter; + return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.GramPerHourPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromGramsPerHourPerSquareMeter(QuantityValue gramsperhourpersquaremeter) + { + double value = (double) gramsperhourpersquaremeter; + return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.GramPerHourPerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromGramsPerHourPerSquareMillimeter(QuantityValue gramsperhourpersquaremillimeter) + { + double value = (double) gramsperhourpersquaremillimeter; + return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.GramPerSecondPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromGramsPerSecondPerSquareCentimeter(QuantityValue gramspersecondpersquarecentimeter) + { + double value = (double) gramspersecondpersquarecentimeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.GramPerSecondPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) + { + double value = (double) gramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.GramPerSecondPerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromGramsPerSecondPerSquareMillimeter(QuantityValue gramspersecondpersquaremillimeter) + { + double value = (double) gramspersecondpersquaremillimeter; + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.KilogramPerHourPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromKilogramsPerHourPerSquareCentimeter(QuantityValue kilogramsperhourpersquarecentimeter) + { + double value = (double) kilogramsperhourpersquarecentimeter; + return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.KilogramPerHourPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromKilogramsPerHourPerSquareMeter(QuantityValue kilogramsperhourpersquaremeter) + { + double value = (double) kilogramsperhourpersquaremeter; + return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.KilogramPerHourPerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromKilogramsPerHourPerSquareMillimeter(QuantityValue kilogramsperhourpersquaremillimeter) + { + double value = (double) kilogramsperhourpersquaremillimeter; + return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.KilogramPerSecondPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(QuantityValue kilogramspersecondpersquarecentimeter) + { + double value = (double) kilogramspersecondpersquarecentimeter; + return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.KilogramPerSecondPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) + { + double value = (double) kilogramspersecondpersquaremeter; + return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassFlux"/> from <see cref="MassFluxUnit.KilogramPerSecondPerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(QuantityValue kilogramspersecondpersquaremillimeter) + { + double value = (double) kilogramspersecondpersquaremillimeter; + return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MassFluxUnit" /> to <see cref="MassFlux" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MassFlux unit value.</returns> + public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) + { + return new MassFlux((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MassFlux Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MassFlux Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MassFlux, MassFluxUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MassFlux result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MassFlux result) + { + return QuantityParser.Default.TryParse<MassFlux, MassFluxUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassFluxUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassFluxUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MassFluxUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MassFluxUnit)"/> + public static bool TryParseUnit(string str, out MassFluxUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MassFluxUnit unit) + { + return UnitParser.Default.TryParse<MassFluxUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MassFlux operator -(MassFlux right) + { + return new MassFlux(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassFlux"/> from adding two <see cref="MassFlux"/>.</summary> + public static MassFlux operator +(MassFlux left, MassFlux right) + { + return new MassFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassFlux"/> from subtracting two <see cref="MassFlux"/>.</summary> + public static MassFlux operator -(MassFlux left, MassFlux right) + { + return new MassFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassFlux"/> from multiplying value and <see cref="MassFlux"/>.</summary> + public static MassFlux operator *(double left, MassFlux right) + { + return new MassFlux(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassFlux"/> from multiplying value and <see cref="MassFlux"/>.</summary> + public static MassFlux operator *(MassFlux left, double right) + { + return new MassFlux(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MassFlux"/> from dividing <see cref="MassFlux"/> by value.</summary> + public static MassFlux operator /(MassFlux left, double right) + { + return new MassFlux(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MassFlux"/> by <see cref="MassFlux"/>.</summary> + public static double operator /(MassFlux left, MassFlux right) + { + return left.KilogramsPerSecondPerSquareMeter / right.KilogramsPerSecondPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MassFlux left, MassFlux right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MassFlux left, MassFlux right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MassFlux left, MassFlux right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MassFlux left, MassFlux right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MassFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MassFlux left, MassFlux right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MassFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MassFlux left, MassFlux right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MassFlux otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassFlux"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFlux, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MassFlux other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MassFlux"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MassFlux otherQuantity)) throw new ArgumentException("Expected type MassFlux.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MassFlux"/> with another <see cref="MassFlux"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MassFlux other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MassFlux within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MassFlux.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MassFluxUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MassFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MassFlux to another MassFlux with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MassFlux with the specified unit.</returns> + public MassFlux ToUnit(MassFluxUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MassFlux"/> to another <see cref="MassFlux"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MassFlux with the specified unit.</returns> + public MassFlux ToUnit(MassFluxUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MassFlux), Unit, typeof(MassFlux), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MassFlux)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MassFlux"/> to another <see cref="MassFlux"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MassFlux"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MassFluxUnit unit, [NotNullWhen(true)] out MassFlux? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MassFlux? convertedOrNull = (Unit, unit) switch + { + // MassFluxUnit -> BaseUnit + (MassFluxUnit.GramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 3.6e2, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.GramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 3.6e6, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.GramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 3.6e0, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.GramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 1e-1, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.GramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 1e3, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.GramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 1e-3, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.KilogramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 3.6e2) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.KilogramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 3.6e6) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.KilogramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 3.6e0) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.KilogramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 1e-1) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), + (MassFluxUnit.KilogramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 1e-3) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), + + // BaseUnit -> MassFluxUnit + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareCentimeter) => new MassFlux(_value * 3.6e2, MassFluxUnit.GramPerHourPerSquareCentimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMeter) => new MassFlux(_value * 3.6e6, MassFluxUnit.GramPerHourPerSquareMeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMillimeter) => new MassFlux(_value * 3.6e0, MassFluxUnit.GramPerHourPerSquareMillimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareCentimeter) => new MassFlux(_value * 1e-1, MassFluxUnit.GramPerSecondPerSquareCentimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMeter) => new MassFlux(_value * 1e3, MassFluxUnit.GramPerSecondPerSquareMeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMillimeter) => new MassFlux(_value * 1e-3, MassFluxUnit.GramPerSecondPerSquareMillimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareCentimeter) => new MassFlux((_value * 3.6e2) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareCentimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMeter) => new MassFlux((_value * 3.6e6) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareMeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMillimeter) => new MassFlux((_value * 3.6e0) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareMillimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareCentimeter) => new MassFlux((_value * 1e-1) / 1e3d, MassFluxUnit.KilogramPerSecondPerSquareCentimeter), + (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMillimeter) => new MassFlux((_value * 1e-3) / 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MassFluxUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MassFluxUnit> IQuantity<MassFluxUnit>.ToUnit(MassFluxUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MassFluxUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFlux)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFlux)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFlux)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MassFlux)) + return this; + else if (conversionType == typeof(MassFluxUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MassFlux.Info; + else if (conversionType == typeof(BaseDimensions)) + return MassFlux.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MassFlux)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MassFlux/MassFluxUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MassFlux/MassFluxUnit.g.cs new file mode 100644 index 0000000000..def9d86acb --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFlux/MassFluxUnit.g.cs @@ -0,0 +1,43 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MassFluxUnit + { + GramPerHourPerSquareCentimeter = 1, + GramPerHourPerSquareMeter = 2, + GramPerHourPerSquareMillimeter = 3, + GramPerSecondPerSquareCentimeter = 4, + GramPerSecondPerSquareMeter = 5, + GramPerSecondPerSquareMillimeter = 6, + KilogramPerHourPerSquareCentimeter = 7, + KilogramPerHourPerSquareMeter = 8, + KilogramPerHourPerSquareMillimeter = 9, + KilogramPerSecondPerSquareCentimeter = 10, + KilogramPerSecondPerSquareMeter = 11, + KilogramPerSecondPerSquareMillimeter = 12, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MassFraction/MassFraction.csproj b/UnitsNet.Modular/GeneratedCode/MassFraction/MassFraction.csproj new file mode 100644 index 0000000000..597d455411 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFraction/MassFraction.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MassFraction</Title> + <Description>Adds MassFraction units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>massfraction unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{db140d08-4769-dc51-8809-a9222b830ef4}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MassFraction</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MassFraction/MassFraction.g.cs b/UnitsNet.Modular/GeneratedCode/MassFraction/MassFraction.g.cs new file mode 100644 index 0000000000..0303efa248 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFraction/MassFraction.g.cs @@ -0,0 +1,1324 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The mass fraction is defined as the mass of a constituent divided by the total mass of the mixture. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Mass_fraction_(chemistry) + /// </remarks> + [DataContract] + public readonly partial struct MassFraction : IArithmeticQuantity<MassFraction, MassFractionUnit, double>, IEquatable<MassFraction>, IComparable, IComparable<MassFraction>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MassFractionUnit? _unit; + + static MassFraction() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = MassFractionUnit.DecimalFraction; + Units = Enum.GetValues(typeof(MassFractionUnit)).Cast<MassFractionUnit>().ToArray(); + Zero = new MassFraction(0, BaseUnit); + Info = new QuantityInfo<MassFractionUnit>("MassFraction", + new UnitInfo<MassFractionUnit>[] + { + new UnitInfo<MassFractionUnit>(MassFractionUnit.CentigramPerGram, "CentigramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.CentigramPerKilogram, "CentigramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.DecagramPerGram, "DecagramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.DecagramPerKilogram, "DecagramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.DecigramPerGram, "DecigramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.DecigramPerKilogram, "DecigramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.DecimalFraction, "DecimalFractions", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.GramPerGram, "GramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.GramPerKilogram, "GramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.HectogramPerGram, "HectogramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.HectogramPerKilogram, "HectogramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.KilogramPerGram, "KilogramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.KilogramPerKilogram, "KilogramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.MicrogramPerGram, "MicrogramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.MicrogramPerKilogram, "MicrogramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.MilligramPerGram, "MilligramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.MilligramPerKilogram, "MilligramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.NanogramPerGram, "NanogramsPerGram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.NanogramPerKilogram, "NanogramsPerKilogram", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.PartPerBillion, "PartsPerBillion", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.PartPerMillion, "PartsPerMillion", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.PartPerThousand, "PartsPerThousand", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined), + new UnitInfo<MassFractionUnit>(MassFractionUnit.Percent, "Percent", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MassFraction(double value, MassFractionUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MassFraction" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MassFractionUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MassFraction, which is DecimalFraction. All conversions go via this value. + /// </summary> + public static MassFractionUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MassFraction quantity. + /// </summary> + public static MassFractionUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// </summary> + public static MassFraction Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MassFraction AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MassFractionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MassFractionUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MassFraction.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.CentigramPerGram"/> + /// </summary> + public double CentigramsPerGram => As(MassFractionUnit.CentigramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.CentigramPerKilogram"/> + /// </summary> + public double CentigramsPerKilogram => As(MassFractionUnit.CentigramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.DecagramPerGram"/> + /// </summary> + public double DecagramsPerGram => As(MassFractionUnit.DecagramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.DecagramPerKilogram"/> + /// </summary> + public double DecagramsPerKilogram => As(MassFractionUnit.DecagramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.DecigramPerGram"/> + /// </summary> + public double DecigramsPerGram => As(MassFractionUnit.DecigramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.DecigramPerKilogram"/> + /// </summary> + public double DecigramsPerKilogram => As(MassFractionUnit.DecigramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.DecimalFraction"/> + /// </summary> + public double DecimalFractions => As(MassFractionUnit.DecimalFraction); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.GramPerGram"/> + /// </summary> + public double GramsPerGram => As(MassFractionUnit.GramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.GramPerKilogram"/> + /// </summary> + public double GramsPerKilogram => As(MassFractionUnit.GramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.HectogramPerGram"/> + /// </summary> + public double HectogramsPerGram => As(MassFractionUnit.HectogramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.HectogramPerKilogram"/> + /// </summary> + public double HectogramsPerKilogram => As(MassFractionUnit.HectogramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.KilogramPerGram"/> + /// </summary> + public double KilogramsPerGram => As(MassFractionUnit.KilogramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.KilogramPerKilogram"/> + /// </summary> + public double KilogramsPerKilogram => As(MassFractionUnit.KilogramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.MicrogramPerGram"/> + /// </summary> + public double MicrogramsPerGram => As(MassFractionUnit.MicrogramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.MicrogramPerKilogram"/> + /// </summary> + public double MicrogramsPerKilogram => As(MassFractionUnit.MicrogramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.MilligramPerGram"/> + /// </summary> + public double MilligramsPerGram => As(MassFractionUnit.MilligramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.MilligramPerKilogram"/> + /// </summary> + public double MilligramsPerKilogram => As(MassFractionUnit.MilligramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.NanogramPerGram"/> + /// </summary> + public double NanogramsPerGram => As(MassFractionUnit.NanogramPerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.NanogramPerKilogram"/> + /// </summary> + public double NanogramsPerKilogram => As(MassFractionUnit.NanogramPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.PartPerBillion"/> + /// </summary> + public double PartsPerBillion => As(MassFractionUnit.PartPerBillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.PartPerMillion"/> + /// </summary> + public double PartsPerMillion => As(MassFractionUnit.PartPerMillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.PartPerThousand"/> + /// </summary> + public double PartsPerThousand => As(MassFractionUnit.PartPerThousand); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.PartPerTrillion"/> + /// </summary> + public double PartsPerTrillion => As(MassFractionUnit.PartPerTrillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassFractionUnit.Percent"/> + /// </summary> + public double Percent => As(MassFractionUnit.Percent); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MassFractionUnit -> BaseUnit + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.CentigramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.CentigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecagramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecagramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecigramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.GramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.GramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.HectogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.HectogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.KilogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.KilogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.MicrogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.MicrogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.MilligramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.MilligramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.NanogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.NanogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.PartPerBillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.PartPerMillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.PartPerThousand, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.PartPerTrillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.Percent, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.DecimalFraction, quantity => quantity); + + // Register in unit converter: BaseUnit -> MassFractionUnit + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerGram, quantity => quantity.ToUnit(MassFractionUnit.CentigramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.CentigramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerGram, quantity => quantity.ToUnit(MassFractionUnit.DecagramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.DecagramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerGram, quantity => quantity.ToUnit(MassFractionUnit.DecigramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.DecigramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerGram, quantity => quantity.ToUnit(MassFractionUnit.GramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.GramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.HectogramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.HectogramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.KilogramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.KilogramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.MicrogramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.MicrogramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerGram, quantity => quantity.ToUnit(MassFractionUnit.MilligramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.MilligramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.NanogramPerGram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.NanogramPerKilogram)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerBillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerBillion)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerMillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerMillion)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerThousand, quantity => quantity.ToUnit(MassFractionUnit.PartPerThousand)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerTrillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerTrillion)); + unitConverter.SetConversionFunction<MassFraction>(MassFractionUnit.DecimalFraction, MassFractionUnit.Percent, quantity => quantity.ToUnit(MassFractionUnit.Percent)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.CentigramPerGram, new CultureInfo("en-US"), false, true, new string[]{"cg/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.CentigramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"cg/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.DecagramPerGram, new CultureInfo("en-US"), false, true, new string[]{"dag/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.DecagramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"dag/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.DecigramPerGram, new CultureInfo("en-US"), false, true, new string[]{"dg/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.DecigramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"dg/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.DecimalFraction, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.GramPerGram, new CultureInfo("en-US"), false, true, new string[]{"g/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.GramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"g/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.HectogramPerGram, new CultureInfo("en-US"), false, true, new string[]{"hg/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.HectogramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"hg/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.KilogramPerGram, new CultureInfo("en-US"), false, true, new string[]{"kg/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.KilogramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"kg/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.MicrogramPerGram, new CultureInfo("en-US"), false, true, new string[]{"µg/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.MicrogramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"µg/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.MilligramPerGram, new CultureInfo("en-US"), false, true, new string[]{"mg/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.MilligramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"mg/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.NanogramPerGram, new CultureInfo("en-US"), false, true, new string[]{"ng/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.NanogramPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"ng/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.PartPerBillion, new CultureInfo("en-US"), false, true, new string[]{"ppb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.PartPerMillion, new CultureInfo("en-US"), false, true, new string[]{"ppm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.PartPerThousand, new CultureInfo("en-US"), false, true, new string[]{"‰"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.PartPerTrillion, new CultureInfo("en-US"), false, true, new string[]{"ppt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassFractionUnit.Percent, new CultureInfo("en-US"), false, true, new string[]{"%", "% (w/w)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MassFractionUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MassFractionUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.CentigramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromCentigramsPerGram(QuantityValue centigramspergram) + { + double value = (double) centigramspergram; + return new MassFraction(value, MassFractionUnit.CentigramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.CentigramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromCentigramsPerKilogram(QuantityValue centigramsperkilogram) + { + double value = (double) centigramsperkilogram; + return new MassFraction(value, MassFractionUnit.CentigramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.DecagramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromDecagramsPerGram(QuantityValue decagramspergram) + { + double value = (double) decagramspergram; + return new MassFraction(value, MassFractionUnit.DecagramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.DecagramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromDecagramsPerKilogram(QuantityValue decagramsperkilogram) + { + double value = (double) decagramsperkilogram; + return new MassFraction(value, MassFractionUnit.DecagramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.DecigramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromDecigramsPerGram(QuantityValue decigramspergram) + { + double value = (double) decigramspergram; + return new MassFraction(value, MassFractionUnit.DecigramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.DecigramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromDecigramsPerKilogram(QuantityValue decigramsperkilogram) + { + double value = (double) decigramsperkilogram; + return new MassFraction(value, MassFractionUnit.DecigramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.DecimalFraction"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromDecimalFractions(QuantityValue decimalfractions) + { + double value = (double) decimalfractions; + return new MassFraction(value, MassFractionUnit.DecimalFraction); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.GramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromGramsPerGram(QuantityValue gramspergram) + { + double value = (double) gramspergram; + return new MassFraction(value, MassFractionUnit.GramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.GramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromGramsPerKilogram(QuantityValue gramsperkilogram) + { + double value = (double) gramsperkilogram; + return new MassFraction(value, MassFractionUnit.GramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.HectogramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromHectogramsPerGram(QuantityValue hectogramspergram) + { + double value = (double) hectogramspergram; + return new MassFraction(value, MassFractionUnit.HectogramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.HectogramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromHectogramsPerKilogram(QuantityValue hectogramsperkilogram) + { + double value = (double) hectogramsperkilogram; + return new MassFraction(value, MassFractionUnit.HectogramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.KilogramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromKilogramsPerGram(QuantityValue kilogramspergram) + { + double value = (double) kilogramspergram; + return new MassFraction(value, MassFractionUnit.KilogramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.KilogramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromKilogramsPerKilogram(QuantityValue kilogramsperkilogram) + { + double value = (double) kilogramsperkilogram; + return new MassFraction(value, MassFractionUnit.KilogramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.MicrogramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromMicrogramsPerGram(QuantityValue microgramspergram) + { + double value = (double) microgramspergram; + return new MassFraction(value, MassFractionUnit.MicrogramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.MicrogramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromMicrogramsPerKilogram(QuantityValue microgramsperkilogram) + { + double value = (double) microgramsperkilogram; + return new MassFraction(value, MassFractionUnit.MicrogramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.MilligramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromMilligramsPerGram(QuantityValue milligramspergram) + { + double value = (double) milligramspergram; + return new MassFraction(value, MassFractionUnit.MilligramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.MilligramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromMilligramsPerKilogram(QuantityValue milligramsperkilogram) + { + double value = (double) milligramsperkilogram; + return new MassFraction(value, MassFractionUnit.MilligramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.NanogramPerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromNanogramsPerGram(QuantityValue nanogramspergram) + { + double value = (double) nanogramspergram; + return new MassFraction(value, MassFractionUnit.NanogramPerGram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.NanogramPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromNanogramsPerKilogram(QuantityValue nanogramsperkilogram) + { + double value = (double) nanogramsperkilogram; + return new MassFraction(value, MassFractionUnit.NanogramPerKilogram); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.PartPerBillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromPartsPerBillion(QuantityValue partsperbillion) + { + double value = (double) partsperbillion; + return new MassFraction(value, MassFractionUnit.PartPerBillion); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.PartPerMillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromPartsPerMillion(QuantityValue partspermillion) + { + double value = (double) partspermillion; + return new MassFraction(value, MassFractionUnit.PartPerMillion); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.PartPerThousand"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromPartsPerThousand(QuantityValue partsperthousand) + { + double value = (double) partsperthousand; + return new MassFraction(value, MassFractionUnit.PartPerThousand); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.PartPerTrillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromPartsPerTrillion(QuantityValue partspertrillion) + { + double value = (double) partspertrillion; + return new MassFraction(value, MassFractionUnit.PartPerTrillion); + } + + /// <summary> + /// Creates a <see cref="MassFraction"/> from <see cref="MassFractionUnit.Percent"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassFraction FromPercent(QuantityValue percent) + { + double value = (double) percent; + return new MassFraction(value, MassFractionUnit.Percent); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MassFractionUnit" /> to <see cref="MassFraction" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MassFraction unit value.</returns> + public static MassFraction From(QuantityValue value, MassFractionUnit fromUnit) + { + return new MassFraction((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MassFraction Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MassFraction Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MassFraction, MassFractionUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MassFraction result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MassFraction result) + { + return QuantityParser.Default.TryParse<MassFraction, MassFractionUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassFractionUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassFractionUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MassFractionUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MassFractionUnit)"/> + public static bool TryParseUnit(string str, out MassFractionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MassFractionUnit unit) + { + return UnitParser.Default.TryParse<MassFractionUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MassFraction operator -(MassFraction right) + { + return new MassFraction(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassFraction"/> from adding two <see cref="MassFraction"/>.</summary> + public static MassFraction operator +(MassFraction left, MassFraction right) + { + return new MassFraction(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassFraction"/> from subtracting two <see cref="MassFraction"/>.</summary> + public static MassFraction operator -(MassFraction left, MassFraction right) + { + return new MassFraction(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassFraction"/> from multiplying value and <see cref="MassFraction"/>.</summary> + public static MassFraction operator *(double left, MassFraction right) + { + return new MassFraction(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassFraction"/> from multiplying value and <see cref="MassFraction"/>.</summary> + public static MassFraction operator *(MassFraction left, double right) + { + return new MassFraction(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MassFraction"/> from dividing <see cref="MassFraction"/> by value.</summary> + public static MassFraction operator /(MassFraction left, double right) + { + return new MassFraction(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MassFraction"/> by <see cref="MassFraction"/>.</summary> + public static double operator /(MassFraction left, MassFraction right) + { + return left.DecimalFractions / right.DecimalFractions; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MassFraction left, MassFraction right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MassFraction left, MassFraction right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MassFraction left, MassFraction right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MassFraction left, MassFraction right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MassFraction"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFraction, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MassFraction left, MassFraction right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MassFraction"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFraction, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MassFraction left, MassFraction right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassFraction"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFraction, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MassFraction otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassFraction"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassFraction, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MassFraction other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MassFraction"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MassFraction otherQuantity)) throw new ArgumentException("Expected type MassFraction.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MassFraction"/> with another <see cref="MassFraction"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MassFraction other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MassFraction within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(MassFraction other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MassFraction.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MassFractionUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MassFractionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MassFraction to another MassFraction with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MassFraction with the specified unit.</returns> + public MassFraction ToUnit(MassFractionUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MassFraction"/> to another <see cref="MassFraction"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MassFraction with the specified unit.</returns> + public MassFraction ToUnit(MassFractionUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MassFraction), Unit, typeof(MassFraction), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MassFraction)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MassFraction"/> to another <see cref="MassFraction"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MassFraction"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MassFractionUnit unit, [NotNullWhen(true)] out MassFraction? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MassFraction? convertedOrNull = (Unit, unit) switch + { + // MassFractionUnit -> BaseUnit + (MassFractionUnit.CentigramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-2d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.CentigramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-2d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.DecagramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e1d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.DecagramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e1d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.DecigramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-1d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.DecigramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-1d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.GramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction(_value, MassFractionUnit.DecimalFraction), + (MassFractionUnit.GramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e3, MassFractionUnit.DecimalFraction), + (MassFractionUnit.HectogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e2d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.HectogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e2d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.KilogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e3d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.KilogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e3d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.MicrogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-6d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.MicrogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-6d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.MilligramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-3d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.MilligramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-3d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.NanogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-9d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.NanogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-9d, MassFractionUnit.DecimalFraction), + (MassFractionUnit.PartPerBillion, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e9, MassFractionUnit.DecimalFraction), + (MassFractionUnit.PartPerMillion, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e6, MassFractionUnit.DecimalFraction), + (MassFractionUnit.PartPerThousand, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e3, MassFractionUnit.DecimalFraction), + (MassFractionUnit.PartPerTrillion, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e12, MassFractionUnit.DecimalFraction), + (MassFractionUnit.Percent, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e2, MassFractionUnit.DecimalFraction), + + // BaseUnit -> MassFractionUnit + (MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerGram) => new MassFraction((_value) / 1e-2d, MassFractionUnit.CentigramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerKilogram) => new MassFraction((_value * 1e3) / 1e-2d, MassFractionUnit.CentigramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerGram) => new MassFraction((_value) / 1e1d, MassFractionUnit.DecagramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerKilogram) => new MassFraction((_value * 1e3) / 1e1d, MassFractionUnit.DecagramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerGram) => new MassFraction((_value) / 1e-1d, MassFractionUnit.DecigramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerKilogram) => new MassFraction((_value * 1e3) / 1e-1d, MassFractionUnit.DecigramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerGram) => new MassFraction(_value, MassFractionUnit.GramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerKilogram) => new MassFraction(_value * 1e3, MassFractionUnit.GramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerGram) => new MassFraction((_value) / 1e2d, MassFractionUnit.HectogramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerKilogram) => new MassFraction((_value * 1e3) / 1e2d, MassFractionUnit.HectogramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerGram) => new MassFraction((_value) / 1e3d, MassFractionUnit.KilogramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerKilogram) => new MassFraction((_value * 1e3) / 1e3d, MassFractionUnit.KilogramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerGram) => new MassFraction((_value) / 1e-6d, MassFractionUnit.MicrogramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerKilogram) => new MassFraction((_value * 1e3) / 1e-6d, MassFractionUnit.MicrogramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerGram) => new MassFraction((_value) / 1e-3d, MassFractionUnit.MilligramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerKilogram) => new MassFraction((_value * 1e3) / 1e-3d, MassFractionUnit.MilligramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerGram) => new MassFraction((_value) / 1e-9d, MassFractionUnit.NanogramPerGram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerKilogram) => new MassFraction((_value * 1e3) / 1e-9d, MassFractionUnit.NanogramPerKilogram), + (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerBillion) => new MassFraction(_value * 1e9, MassFractionUnit.PartPerBillion), + (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerMillion) => new MassFraction(_value * 1e6, MassFractionUnit.PartPerMillion), + (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerThousand) => new MassFraction(_value * 1e3, MassFractionUnit.PartPerThousand), + (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerTrillion) => new MassFraction(_value * 1e12, MassFractionUnit.PartPerTrillion), + (MassFractionUnit.DecimalFraction, MassFractionUnit.Percent) => new MassFraction(_value * 1e2, MassFractionUnit.Percent), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MassFractionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MassFractionUnit> IQuantity<MassFractionUnit>.ToUnit(MassFractionUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MassFractionUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFraction)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFraction)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassFraction)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MassFraction)) + return this; + else if (conversionType == typeof(MassFractionUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MassFraction.Info; + else if (conversionType == typeof(BaseDimensions)) + return MassFraction.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MassFraction)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MassFraction/MassFractionUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MassFraction/MassFractionUnit.g.cs new file mode 100644 index 0000000000..0dad8a059f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassFraction/MassFractionUnit.g.cs @@ -0,0 +1,55 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MassFractionUnit + { + CentigramPerGram = 1, + CentigramPerKilogram = 2, + DecagramPerGram = 3, + DecagramPerKilogram = 4, + DecigramPerGram = 5, + DecigramPerKilogram = 6, + DecimalFraction = 7, + GramPerGram = 8, + GramPerKilogram = 9, + HectogramPerGram = 10, + HectogramPerKilogram = 11, + KilogramPerGram = 12, + KilogramPerKilogram = 13, + MicrogramPerGram = 14, + MicrogramPerKilogram = 15, + MilligramPerGram = 16, + MilligramPerKilogram = 17, + NanogramPerGram = 18, + NanogramPerKilogram = 19, + PartPerBillion = 20, + PartPerMillion = 21, + PartPerThousand = 22, + PartPerTrillion = 23, + Percent = 24, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertia.csproj b/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertia.csproj new file mode 100644 index 0000000000..0ebbf43dfd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertia.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MassMomentOfInertia</Title> + <Description>Adds MassMomentOfInertia units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>massmomentofinertia unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{6218c061-3905-79b2-d3bc-bb7b8fc77a69}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MassMomentOfInertia</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertia.g.cs b/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertia.g.cs new file mode 100644 index 0000000000..32b45fcc2a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertia.g.cs @@ -0,0 +1,1405 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// A property of body reflects how its mass is distributed with regard to an axis. + /// </summary> + [DataContract] + public readonly partial struct MassMomentOfInertia : IArithmeticQuantity<MassMomentOfInertia, MassMomentOfInertiaUnit, double>, IEquatable<MassMomentOfInertia>, IComparable, IComparable<MassMomentOfInertia>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MassMomentOfInertiaUnit? _unit; + + static MassMomentOfInertia() + { + BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); + BaseUnit = MassMomentOfInertiaUnit.KilogramSquareMeter; + Units = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast<MassMomentOfInertiaUnit>().ToArray(); + Zero = new MassMomentOfInertia(0, BaseUnit); + Info = new QuantityInfo<MassMomentOfInertiaUnit>("MassMomentOfInertia", + new UnitInfo<MassMomentOfInertiaUnit>[] + { + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.GramSquareCentimeter, "GramSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.GramSquareDecimeter, "GramSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.GramSquareMeter, "GramSquareMeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.GramSquareMillimeter, "GramSquareMillimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilogramSquareCentimeter, "KilogramSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilogramSquareDecimeter, "KilogramSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilogramSquareMeter, "KilogramSquareMeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilogramSquareMillimeter, "KilogramSquareMillimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, "KilotonneSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, "KilotonneSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilotonneSquareMeter, "KilotonneSquareMeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, "KilotonneSquareMilimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, "MegatonneSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, "MegatonneSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MegatonneSquareMeter, "MegatonneSquareMeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, "MegatonneSquareMilimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MilligramSquareCentimeter, "MilligramSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MilligramSquareDecimeter, "MilligramSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MilligramSquareMeter, "MilligramSquareMeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.MilligramSquareMillimeter, "MilligramSquareMillimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.PoundSquareFoot, "PoundSquareFeet", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.PoundSquareInch, "PoundSquareInches", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.SlugSquareFoot, "SlugSquareFeet", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.SlugSquareInch, "SlugSquareInches", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.TonneSquareCentimeter, "TonneSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.TonneSquareDecimeter, "TonneSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.TonneSquareMeter, "TonneSquareMeters", BaseUnits.Undefined), + new UnitInfo<MassMomentOfInertiaUnit>(MassMomentOfInertiaUnit.TonneSquareMilimeter, "TonneSquareMilimeters", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MassMomentOfInertia(double value, MassMomentOfInertiaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MassMomentOfInertia" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MassMomentOfInertiaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. + /// </summary> + public static MassMomentOfInertiaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MassMomentOfInertia quantity. + /// </summary> + public static MassMomentOfInertiaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. + /// </summary> + public static MassMomentOfInertia Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MassMomentOfInertia AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MassMomentOfInertiaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.GramSquareCentimeter"/> + /// </summary> + public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.GramSquareDecimeter"/> + /// </summary> + public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.GramSquareMeter"/> + /// </summary> + public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.GramSquareMillimeter"/> + /// </summary> + public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilogramSquareCentimeter"/> + /// </summary> + public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilogramSquareDecimeter"/> + /// </summary> + public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilogramSquareMeter"/> + /// </summary> + public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilogramSquareMillimeter"/> + /// </summary> + public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilotonneSquareCentimeter"/> + /// </summary> + public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilotonneSquareDecimeter"/> + /// </summary> + public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilotonneSquareMeter"/> + /// </summary> + public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.KilotonneSquareMilimeter"/> + /// </summary> + public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MegatonneSquareCentimeter"/> + /// </summary> + public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MegatonneSquareDecimeter"/> + /// </summary> + public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MegatonneSquareMeter"/> + /// </summary> + public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MegatonneSquareMilimeter"/> + /// </summary> + public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MilligramSquareCentimeter"/> + /// </summary> + public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MilligramSquareDecimeter"/> + /// </summary> + public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MilligramSquareMeter"/> + /// </summary> + public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.MilligramSquareMillimeter"/> + /// </summary> + public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.PoundSquareFoot"/> + /// </summary> + public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.PoundSquareInch"/> + /// </summary> + public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.SlugSquareFoot"/> + /// </summary> + public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.SlugSquareInch"/> + /// </summary> + public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.TonneSquareCentimeter"/> + /// </summary> + public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.TonneSquareDecimeter"/> + /// </summary> + public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.TonneSquareMeter"/> + /// </summary> + public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MassMomentOfInertiaUnit.TonneSquareMilimeter"/> + /// </summary> + public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MassMomentOfInertiaUnit -> BaseUnit + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.GramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.GramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.GramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.GramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilotonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MegatonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MilligramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MilligramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MilligramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.MilligramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.PoundSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.PoundSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.SlugSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.SlugSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.TonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.TonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.TonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.TonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> MassMomentOfInertiaUnit + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareCentimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareDecimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareMillimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareCentimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareDecimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMillimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareCentimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareDecimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMilimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMilimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareCentimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareDecimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMilimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMilimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareCentimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareDecimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMillimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareFoot, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.PoundSquareFoot)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareInch, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.PoundSquareInch)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareFoot, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.SlugSquareFoot)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareInch, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.SlugSquareInch)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareCentimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareDecimeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareMeter)); + unitConverter.SetConversionFunction<MassMomentOfInertia>(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMilimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareMilimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.GramSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"g·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.GramSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"g·dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.GramSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"g·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.GramSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"g·mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilogramSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilogramSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilogramSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kg·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilogramSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kg·mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kt·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"kt·dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilotonneSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kt·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.KilotonneSquareMilimeter, new CultureInfo("en-US"), false, true, new string[]{"kt·mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"Mt·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"Mt·dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MegatonneSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"Mt·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MegatonneSquareMilimeter, new CultureInfo("en-US"), false, true, new string[]{"Mt·mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MilligramSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"mg·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MilligramSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"mg·dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MilligramSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"mg·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.MilligramSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mg·mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.PoundSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"lb·ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.PoundSquareInch, new CultureInfo("en-US"), false, true, new string[]{"lb·in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.SlugSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"slug·ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.SlugSquareInch, new CultureInfo("en-US"), false, true, new string[]{"slug·in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.TonneSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"t·cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.TonneSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"t·dm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.TonneSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"t·m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MassMomentOfInertiaUnit.TonneSquareMilimeter, new CultureInfo("en-US"), false, true, new string[]{"t·mm²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MassMomentOfInertiaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MassMomentOfInertiaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.GramSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) + { + double value = (double) gramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.GramSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) + { + double value = (double) gramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.GramSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) + { + double value = (double) gramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.GramSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) + { + double value = (double) gramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilogramSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) + { + double value = (double) kilogramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilogramSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) + { + double value = (double) kilogramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilogramSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) + { + double value = (double) kilogramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilogramSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) + { + double value = (double) kilogramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilotonneSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) + { + double value = (double) kilotonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilotonneSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) + { + double value = (double) kilotonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilotonneSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) + { + double value = (double) kilotonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.KilotonneSquareMilimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) + { + double value = (double) kilotonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MegatonneSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) + { + double value = (double) megatonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MegatonneSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) + { + double value = (double) megatonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MegatonneSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) + { + double value = (double) megatonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MegatonneSquareMilimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) + { + double value = (double) megatonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MilligramSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) + { + double value = (double) milligramsquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MilligramSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) + { + double value = (double) milligramsquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MilligramSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) + { + double value = (double) milligramsquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.MilligramSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) + { + double value = (double) milligramsquaremillimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.PoundSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) + { + double value = (double) poundsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.PoundSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) + { + double value = (double) poundsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.SlugSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue slugsquarefeet) + { + double value = (double) slugsquarefeet; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.SlugSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromSlugSquareInches(QuantityValue slugsquareinches) + { + double value = (double) slugsquareinches; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.TonneSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) + { + double value = (double) tonnesquarecentimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.TonneSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) + { + double value = (double) tonnesquaredecimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.TonneSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) + { + double value = (double) tonnesquaremeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); + } + + /// <summary> + /// Creates a <see cref="MassMomentOfInertia"/> from <see cref="MassMomentOfInertiaUnit.TonneSquareMilimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) + { + double value = (double) tonnesquaremilimeters; + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MassMomentOfInertiaUnit" /> to <see cref="MassMomentOfInertia" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MassMomentOfInertia unit value.</returns> + public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) + { + return new MassMomentOfInertia((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MassMomentOfInertia Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MassMomentOfInertia Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MassMomentOfInertia, MassMomentOfInertiaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MassMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MassMomentOfInertia result) + { + return QuantityParser.Default.TryParse<MassMomentOfInertia, MassMomentOfInertiaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassMomentOfInertiaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MassMomentOfInertiaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MassMomentOfInertiaUnit)"/> + public static bool TryParseUnit(string str, out MassMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MassMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse<MassMomentOfInertiaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MassMomentOfInertia operator -(MassMomentOfInertia right) + { + return new MassMomentOfInertia(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassMomentOfInertia"/> from adding two <see cref="MassMomentOfInertia"/>.</summary> + public static MassMomentOfInertia operator +(MassMomentOfInertia left, MassMomentOfInertia right) + { + return new MassMomentOfInertia(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassMomentOfInertia"/> from subtracting two <see cref="MassMomentOfInertia"/>.</summary> + public static MassMomentOfInertia operator -(MassMomentOfInertia left, MassMomentOfInertia right) + { + return new MassMomentOfInertia(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MassMomentOfInertia"/> from multiplying value and <see cref="MassMomentOfInertia"/>.</summary> + public static MassMomentOfInertia operator *(double left, MassMomentOfInertia right) + { + return new MassMomentOfInertia(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MassMomentOfInertia"/> from multiplying value and <see cref="MassMomentOfInertia"/>.</summary> + public static MassMomentOfInertia operator *(MassMomentOfInertia left, double right) + { + return new MassMomentOfInertia(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MassMomentOfInertia"/> from dividing <see cref="MassMomentOfInertia"/> by value.</summary> + public static MassMomentOfInertia operator /(MassMomentOfInertia left, double right) + { + return new MassMomentOfInertia(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MassMomentOfInertia"/> by <see cref="MassMomentOfInertia"/>.</summary> + public static double operator /(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.KilogramSquareMeters / right.KilogramSquareMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MassMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MassMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MassMomentOfInertia otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MassMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MassMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MassMomentOfInertia other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MassMomentOfInertia"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MassMomentOfInertia otherQuantity)) throw new ArgumentException("Expected type MassMomentOfInertia.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MassMomentOfInertia"/> with another <see cref="MassMomentOfInertia"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MassMomentOfInertia other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MassMomentOfInertia within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MassMomentOfInertia.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MassMomentOfInertiaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MassMomentOfInertiaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MassMomentOfInertia with the specified unit.</returns> + public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MassMomentOfInertia"/> to another <see cref="MassMomentOfInertia"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MassMomentOfInertia with the specified unit.</returns> + public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MassMomentOfInertia), Unit, typeof(MassMomentOfInertia), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MassMomentOfInertia)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MassMomentOfInertia"/> to another <see cref="MassMomentOfInertia"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MassMomentOfInertia"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MassMomentOfInertiaUnit unit, [NotNullWhen(true)] out MassMomentOfInertia? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MassMomentOfInertia? convertedOrNull = (Unit, unit) switch + { + // MassMomentOfInertiaUnit -> BaseUnit + (MassMomentOfInertiaUnit.GramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e7, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.GramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e5, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.GramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e3, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.GramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e9, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e7) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e5) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e9) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilotonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e1) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilotonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-1) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilotonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-3) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.KilotonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e3) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MegatonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e1) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MegatonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-1) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MegatonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-3) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MegatonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e3) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MilligramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e7) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MilligramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e5) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MilligramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e3) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.MilligramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e9) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.PoundSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * 4.21401101e-2, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.PoundSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * 2.9263965e-4, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.SlugSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * 1.3558179619, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.SlugSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * 9.41540242e-3, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.TonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e1, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.TonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e-1, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.TonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e-3, MassMomentOfInertiaUnit.KilogramSquareMeter), + (MassMomentOfInertiaUnit.TonneSquareMilimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e3, MassMomentOfInertiaUnit.KilogramSquareMeter), + + // BaseUnit -> MassMomentOfInertiaUnit + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareCentimeter) => new MassMomentOfInertia(_value * 1e7, MassMomentOfInertiaUnit.GramSquareCentimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareDecimeter) => new MassMomentOfInertia(_value * 1e5, MassMomentOfInertiaUnit.GramSquareDecimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMeter) => new MassMomentOfInertia(_value * 1e3, MassMomentOfInertiaUnit.GramSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMillimeter) => new MassMomentOfInertia(_value * 1e9, MassMomentOfInertiaUnit.GramSquareMillimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareCentimeter) => new MassMomentOfInertia((_value * 1e7) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareCentimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareDecimeter) => new MassMomentOfInertia((_value * 1e5) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareDecimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMillimeter) => new MassMomentOfInertia((_value * 1e9) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareMillimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareCentimeter) => new MassMomentOfInertia((_value * 1e1) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareCentimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareDecimeter) => new MassMomentOfInertia((_value * 1e-1) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareDecimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMeter) => new MassMomentOfInertia((_value * 1e-3) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMilimeter) => new MassMomentOfInertia((_value * 1e3) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareMilimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareCentimeter) => new MassMomentOfInertia((_value * 1e1) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareCentimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareDecimeter) => new MassMomentOfInertia((_value * 1e-1) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareDecimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMeter) => new MassMomentOfInertia((_value * 1e-3) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMilimeter) => new MassMomentOfInertia((_value * 1e3) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareMilimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareCentimeter) => new MassMomentOfInertia((_value * 1e7) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareCentimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareDecimeter) => new MassMomentOfInertia((_value * 1e5) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareDecimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMeter) => new MassMomentOfInertia((_value * 1e3) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMillimeter) => new MassMomentOfInertia((_value * 1e9) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareMillimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareFoot) => new MassMomentOfInertia(_value / 4.21401101e-2, MassMomentOfInertiaUnit.PoundSquareFoot), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareInch) => new MassMomentOfInertia(_value / 2.9263965e-4, MassMomentOfInertiaUnit.PoundSquareInch), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareFoot) => new MassMomentOfInertia(_value / 1.3558179619, MassMomentOfInertiaUnit.SlugSquareFoot), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareInch) => new MassMomentOfInertia(_value / 9.41540242e-3, MassMomentOfInertiaUnit.SlugSquareInch), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareCentimeter) => new MassMomentOfInertia(_value * 1e1, MassMomentOfInertiaUnit.TonneSquareCentimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareDecimeter) => new MassMomentOfInertia(_value * 1e-1, MassMomentOfInertiaUnit.TonneSquareDecimeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMeter) => new MassMomentOfInertia(_value * 1e-3, MassMomentOfInertiaUnit.TonneSquareMeter), + (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMilimeter) => new MassMomentOfInertia(_value * 1e3, MassMomentOfInertiaUnit.TonneSquareMilimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MassMomentOfInertiaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MassMomentOfInertiaUnit> IQuantity<MassMomentOfInertiaUnit>.ToUnit(MassMomentOfInertiaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MassMomentOfInertiaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MassMomentOfInertia)) + return this; + else if (conversionType == typeof(MassMomentOfInertiaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MassMomentOfInertia.Info; + else if (conversionType == typeof(BaseDimensions)) + return MassMomentOfInertia.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertiaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertiaUnit.g.cs new file mode 100644 index 0000000000..33c92670cb --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MassMomentOfInertia/MassMomentOfInertiaUnit.g.cs @@ -0,0 +1,59 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MassMomentOfInertiaUnit + { + GramSquareCentimeter = 1, + GramSquareDecimeter = 2, + GramSquareMeter = 3, + GramSquareMillimeter = 4, + KilogramSquareCentimeter = 5, + KilogramSquareDecimeter = 6, + KilogramSquareMeter = 7, + KilogramSquareMillimeter = 8, + KilotonneSquareCentimeter = 9, + KilotonneSquareDecimeter = 10, + KilotonneSquareMeter = 11, + KilotonneSquareMilimeter = 12, + MegatonneSquareCentimeter = 13, + MegatonneSquareDecimeter = 14, + MegatonneSquareMeter = 15, + MegatonneSquareMilimeter = 16, + MilligramSquareCentimeter = 17, + MilligramSquareDecimeter = 18, + MilligramSquareMeter = 19, + MilligramSquareMillimeter = 20, + PoundSquareFoot = 21, + PoundSquareInch = 22, + SlugSquareFoot = 23, + SlugSquareInch = 24, + TonneSquareCentimeter = 25, + TonneSquareDecimeter = 26, + TonneSquareMeter = 27, + TonneSquareMilimeter = 28, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergy.csproj b/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergy.csproj new file mode 100644 index 0000000000..6f78cd338b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MolarEnergy</Title> + <Description>Adds MolarEnergy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>molarenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{9b77d4e0-863d-4a74-c30a-56f7b2bb7cb7}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MolarEnergy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergy.g.cs b/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergy.g.cs new file mode 100644 index 0000000000..0c23a632ed --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergy.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Molar energy is the amount of energy stored in 1 mole of a substance. + /// </summary> + [DataContract] + public readonly partial struct MolarEnergy : IArithmeticQuantity<MolarEnergy, MolarEnergyUnit, double>, IEquatable<MolarEnergy>, IComparable, IComparable<MolarEnergy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MolarEnergyUnit? _unit; + + static MolarEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); + BaseUnit = MolarEnergyUnit.JoulePerMole; + Units = Enum.GetValues(typeof(MolarEnergyUnit)).Cast<MolarEnergyUnit>().ToArray(); + Zero = new MolarEnergy(0, BaseUnit); + Info = new QuantityInfo<MolarEnergyUnit>("MolarEnergy", + new UnitInfo<MolarEnergyUnit>[] + { + new UnitInfo<MolarEnergyUnit>(MolarEnergyUnit.JoulePerMole, "JoulesPerMole", BaseUnits.Undefined), + new UnitInfo<MolarEnergyUnit>(MolarEnergyUnit.KilojoulePerMole, "KilojoulesPerMole", BaseUnits.Undefined), + new UnitInfo<MolarEnergyUnit>(MolarEnergyUnit.MegajoulePerMole, "MegajoulesPerMole", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MolarEnergy(double value, MolarEnergyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MolarEnergy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MolarEnergyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. + /// </summary> + public static MolarEnergyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MolarEnergy quantity. + /// </summary> + public static MolarEnergyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. + /// </summary> + public static MolarEnergy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MolarEnergy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MolarEnergyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarEnergyUnit.JoulePerMole"/> + /// </summary> + public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarEnergyUnit.KilojoulePerMole"/> + /// </summary> + public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarEnergyUnit.MegajoulePerMole"/> + /// </summary> + public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MolarEnergyUnit -> BaseUnit + unitConverter.SetConversionFunction<MolarEnergy>(MolarEnergyUnit.KilojoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.JoulePerMole)); + unitConverter.SetConversionFunction<MolarEnergy>(MolarEnergyUnit.MegajoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.JoulePerMole)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MolarEnergy>(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity); + + // Register in unit converter: BaseUnit -> MolarEnergyUnit + unitConverter.SetConversionFunction<MolarEnergy>(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.KilojoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.KilojoulePerMole)); + unitConverter.SetConversionFunction<MolarEnergy>(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.MegajoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.MegajoulePerMole)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MolarEnergyUnit.JoulePerMole, new CultureInfo("en-US"), false, true, new string[]{"J/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarEnergyUnit.KilojoulePerMole, new CultureInfo("en-US"), false, true, new string[]{"kJ/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarEnergyUnit.MegajoulePerMole, new CultureInfo("en-US"), false, true, new string[]{"MJ/mol"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MolarEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MolarEnergyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MolarEnergy"/> from <see cref="MolarEnergyUnit.JoulePerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) + { + double value = (double) joulespermole; + return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); + } + + /// <summary> + /// Creates a <see cref="MolarEnergy"/> from <see cref="MolarEnergyUnit.KilojoulePerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) + { + double value = (double) kilojoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); + } + + /// <summary> + /// Creates a <see cref="MolarEnergy"/> from <see cref="MolarEnergyUnit.MegajoulePerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) + { + double value = (double) megajoulespermole; + return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MolarEnergyUnit" /> to <see cref="MolarEnergy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MolarEnergy unit value.</returns> + public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) + { + return new MolarEnergy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MolarEnergy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MolarEnergy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MolarEnergy, MolarEnergyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MolarEnergy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MolarEnergy result) + { + return QuantityParser.Default.TryParse<MolarEnergy, MolarEnergyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarEnergyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MolarEnergyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MolarEnergyUnit)"/> + public static bool TryParseUnit(string str, out MolarEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarEnergyUnit unit) + { + return UnitParser.Default.TryParse<MolarEnergyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MolarEnergy operator -(MolarEnergy right) + { + return new MolarEnergy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MolarEnergy"/> from adding two <see cref="MolarEnergy"/>.</summary> + public static MolarEnergy operator +(MolarEnergy left, MolarEnergy right) + { + return new MolarEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MolarEnergy"/> from subtracting two <see cref="MolarEnergy"/>.</summary> + public static MolarEnergy operator -(MolarEnergy left, MolarEnergy right) + { + return new MolarEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MolarEnergy"/> from multiplying value and <see cref="MolarEnergy"/>.</summary> + public static MolarEnergy operator *(double left, MolarEnergy right) + { + return new MolarEnergy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MolarEnergy"/> from multiplying value and <see cref="MolarEnergy"/>.</summary> + public static MolarEnergy operator *(MolarEnergy left, double right) + { + return new MolarEnergy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MolarEnergy"/> from dividing <see cref="MolarEnergy"/> by value.</summary> + public static MolarEnergy operator /(MolarEnergy left, double right) + { + return new MolarEnergy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MolarEnergy"/> by <see cref="MolarEnergy"/>.</summary> + public static double operator /(MolarEnergy left, MolarEnergy right) + { + return left.JoulesPerMole / right.JoulesPerMole; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MolarEnergy left, MolarEnergy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MolarEnergy left, MolarEnergy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MolarEnergy left, MolarEnergy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MolarEnergy left, MolarEnergy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MolarEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MolarEnergy left, MolarEnergy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MolarEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MolarEnergy left, MolarEnergy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MolarEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MolarEnergy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MolarEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MolarEnergy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MolarEnergy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MolarEnergy otherQuantity)) throw new ArgumentException("Expected type MolarEnergy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MolarEnergy"/> with another <see cref="MolarEnergy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MolarEnergy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MolarEnergy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MolarEnergy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MolarEnergyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MolarEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MolarEnergy to another MolarEnergy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MolarEnergy with the specified unit.</returns> + public MolarEnergy ToUnit(MolarEnergyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MolarEnergy"/> to another <see cref="MolarEnergy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MolarEnergy with the specified unit.</returns> + public MolarEnergy ToUnit(MolarEnergyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MolarEnergy), Unit, typeof(MolarEnergy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MolarEnergy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MolarEnergy"/> to another <see cref="MolarEnergy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MolarEnergy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MolarEnergyUnit unit, [NotNullWhen(true)] out MolarEnergy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MolarEnergy? convertedOrNull = (Unit, unit) switch + { + // MolarEnergyUnit -> BaseUnit + (MolarEnergyUnit.KilojoulePerMole, MolarEnergyUnit.JoulePerMole) => new MolarEnergy((_value) * 1e3d, MolarEnergyUnit.JoulePerMole), + (MolarEnergyUnit.MegajoulePerMole, MolarEnergyUnit.JoulePerMole) => new MolarEnergy((_value) * 1e6d, MolarEnergyUnit.JoulePerMole), + + // BaseUnit -> MolarEnergyUnit + (MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.KilojoulePerMole) => new MolarEnergy((_value) / 1e3d, MolarEnergyUnit.KilojoulePerMole), + (MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.MegajoulePerMole) => new MolarEnergy((_value) / 1e6d, MolarEnergyUnit.MegajoulePerMole), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MolarEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MolarEnergyUnit> IQuantity<MolarEnergyUnit>.ToUnit(MolarEnergyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MolarEnergyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MolarEnergy)) + return this; + else if (conversionType == typeof(MolarEnergyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MolarEnergy.Info; + else if (conversionType == typeof(BaseDimensions)) + return MolarEnergy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergyUnit.g.cs new file mode 100644 index 0000000000..71772f28ea --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarEnergy/MolarEnergyUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MolarEnergyUnit + { + JoulePerMole = 1, + KilojoulePerMole = 2, + MegajoulePerMole = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropy.csproj b/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropy.csproj new file mode 100644 index 0000000000..bc770326dd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MolarEntropy</Title> + <Description>Adds MolarEntropy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>molarentropy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{2053731b-90f5-5141-d15e-8d7be8c2662f}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MolarEntropy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropy.g.cs b/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropy.g.cs new file mode 100644 index 0000000000..081cb67fe8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropy.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. + /// </summary> + [DataContract] + public readonly partial struct MolarEntropy : IArithmeticQuantity<MolarEntropy, MolarEntropyUnit, double>, IEquatable<MolarEntropy>, IComparable, IComparable<MolarEntropy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MolarEntropyUnit? _unit; + + static MolarEntropy() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); + BaseUnit = MolarEntropyUnit.JoulePerMoleKelvin; + Units = Enum.GetValues(typeof(MolarEntropyUnit)).Cast<MolarEntropyUnit>().ToArray(); + Zero = new MolarEntropy(0, BaseUnit); + Info = new QuantityInfo<MolarEntropyUnit>("MolarEntropy", + new UnitInfo<MolarEntropyUnit>[] + { + new UnitInfo<MolarEntropyUnit>(MolarEntropyUnit.JoulePerMoleKelvin, "JoulesPerMoleKelvin", BaseUnits.Undefined), + new UnitInfo<MolarEntropyUnit>(MolarEntropyUnit.KilojoulePerMoleKelvin, "KilojoulesPerMoleKelvin", BaseUnits.Undefined), + new UnitInfo<MolarEntropyUnit>(MolarEntropyUnit.MegajoulePerMoleKelvin, "MegajoulesPerMoleKelvin", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MolarEntropy(double value, MolarEntropyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MolarEntropy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MolarEntropyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. + /// </summary> + public static MolarEntropyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MolarEntropy quantity. + /// </summary> + public static MolarEntropyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. + /// </summary> + public static MolarEntropy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MolarEntropy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MolarEntropyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarEntropyUnit.JoulePerMoleKelvin"/> + /// </summary> + public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarEntropyUnit.KilojoulePerMoleKelvin"/> + /// </summary> + public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarEntropyUnit.MegajoulePerMoleKelvin"/> + /// </summary> + public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MolarEntropyUnit -> BaseUnit + unitConverter.SetConversionFunction<MolarEntropy>(MolarEntropyUnit.KilojoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.JoulePerMoleKelvin)); + unitConverter.SetConversionFunction<MolarEntropy>(MolarEntropyUnit.MegajoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.JoulePerMoleKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MolarEntropy>(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> MolarEntropyUnit + unitConverter.SetConversionFunction<MolarEntropy>(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.KilojoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.KilojoulePerMoleKelvin)); + unitConverter.SetConversionFunction<MolarEntropy>(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.MegajoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.MegajoulePerMoleKelvin)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MolarEntropyUnit.JoulePerMoleKelvin, new CultureInfo("en-US"), false, true, new string[]{"J/(mol*K)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarEntropyUnit.KilojoulePerMoleKelvin, new CultureInfo("en-US"), false, true, new string[]{"kJ/(mol*K)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarEntropyUnit.MegajoulePerMoleKelvin, new CultureInfo("en-US"), false, true, new string[]{"MJ/(mol*K)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MolarEntropyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MolarEntropyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MolarEntropy"/> from <see cref="MolarEntropyUnit.JoulePerMoleKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) + { + double value = (double) joulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); + } + + /// <summary> + /// Creates a <see cref="MolarEntropy"/> from <see cref="MolarEntropyUnit.KilojoulePerMoleKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) + { + double value = (double) kilojoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); + } + + /// <summary> + /// Creates a <see cref="MolarEntropy"/> from <see cref="MolarEntropyUnit.MegajoulePerMoleKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) + { + double value = (double) megajoulespermolekelvin; + return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MolarEntropyUnit" /> to <see cref="MolarEntropy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MolarEntropy unit value.</returns> + public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) + { + return new MolarEntropy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MolarEntropy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MolarEntropy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MolarEntropy, MolarEntropyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MolarEntropy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MolarEntropy result) + { + return QuantityParser.Default.TryParse<MolarEntropy, MolarEntropyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarEntropyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarEntropyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MolarEntropyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MolarEntropyUnit)"/> + public static bool TryParseUnit(string str, out MolarEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarEntropyUnit unit) + { + return UnitParser.Default.TryParse<MolarEntropyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MolarEntropy operator -(MolarEntropy right) + { + return new MolarEntropy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MolarEntropy"/> from adding two <see cref="MolarEntropy"/>.</summary> + public static MolarEntropy operator +(MolarEntropy left, MolarEntropy right) + { + return new MolarEntropy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MolarEntropy"/> from subtracting two <see cref="MolarEntropy"/>.</summary> + public static MolarEntropy operator -(MolarEntropy left, MolarEntropy right) + { + return new MolarEntropy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MolarEntropy"/> from multiplying value and <see cref="MolarEntropy"/>.</summary> + public static MolarEntropy operator *(double left, MolarEntropy right) + { + return new MolarEntropy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MolarEntropy"/> from multiplying value and <see cref="MolarEntropy"/>.</summary> + public static MolarEntropy operator *(MolarEntropy left, double right) + { + return new MolarEntropy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MolarEntropy"/> from dividing <see cref="MolarEntropy"/> by value.</summary> + public static MolarEntropy operator /(MolarEntropy left, double right) + { + return new MolarEntropy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MolarEntropy"/> by <see cref="MolarEntropy"/>.</summary> + public static double operator /(MolarEntropy left, MolarEntropy right) + { + return left.JoulesPerMoleKelvin / right.JoulesPerMoleKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MolarEntropy left, MolarEntropy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MolarEntropy left, MolarEntropy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MolarEntropy left, MolarEntropy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MolarEntropy left, MolarEntropy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MolarEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MolarEntropy left, MolarEntropy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MolarEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MolarEntropy left, MolarEntropy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MolarEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MolarEntropy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MolarEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MolarEntropy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MolarEntropy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MolarEntropy otherQuantity)) throw new ArgumentException("Expected type MolarEntropy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MolarEntropy"/> with another <see cref="MolarEntropy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MolarEntropy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MolarEntropy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MolarEntropy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MolarEntropyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MolarEntropyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MolarEntropy to another MolarEntropy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MolarEntropy with the specified unit.</returns> + public MolarEntropy ToUnit(MolarEntropyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MolarEntropy"/> to another <see cref="MolarEntropy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MolarEntropy with the specified unit.</returns> + public MolarEntropy ToUnit(MolarEntropyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MolarEntropy), Unit, typeof(MolarEntropy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MolarEntropy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MolarEntropy"/> to another <see cref="MolarEntropy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MolarEntropy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MolarEntropyUnit unit, [NotNullWhen(true)] out MolarEntropy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MolarEntropy? convertedOrNull = (Unit, unit) switch + { + // MolarEntropyUnit -> BaseUnit + (MolarEntropyUnit.KilojoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin) => new MolarEntropy((_value) * 1e3d, MolarEntropyUnit.JoulePerMoleKelvin), + (MolarEntropyUnit.MegajoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin) => new MolarEntropy((_value) * 1e6d, MolarEntropyUnit.JoulePerMoleKelvin), + + // BaseUnit -> MolarEntropyUnit + (MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.KilojoulePerMoleKelvin) => new MolarEntropy((_value) / 1e3d, MolarEntropyUnit.KilojoulePerMoleKelvin), + (MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.MegajoulePerMoleKelvin) => new MolarEntropy((_value) / 1e6d, MolarEntropyUnit.MegajoulePerMoleKelvin), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MolarEntropyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MolarEntropyUnit> IQuantity<MolarEntropyUnit>.ToUnit(MolarEntropyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MolarEntropyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MolarEntropy)) + return this; + else if (conversionType == typeof(MolarEntropyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MolarEntropy.Info; + else if (conversionType == typeof(BaseDimensions)) + return MolarEntropy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropyUnit.g.cs new file mode 100644 index 0000000000..b7e6c5aa56 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarEntropy/MolarEntropyUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MolarEntropyUnit + { + JoulePerMoleKelvin = 1, + KilojoulePerMoleKelvin = 2, + MegajoulePerMoleKelvin = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMass.csproj b/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMass.csproj new file mode 100644 index 0000000000..e6e00c4d60 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMass.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET MolarMass</Title> + <Description>Adds MolarMass units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>molarmass unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{fe51bbda-2039-23fd-f29a-39c14adcb1f6}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.MolarMass</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMass.g.cs b/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMass.g.cs new file mode 100644 index 0000000000..a070ae57e8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMass.g.cs @@ -0,0 +1,1081 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct MolarMass : IArithmeticQuantity<MolarMass, MolarMassUnit, double>, IEquatable<MolarMass>, IComparable, IComparable<MolarMass>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MolarMassUnit? _unit; + + static MolarMass() + { + BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); + BaseUnit = MolarMassUnit.KilogramPerMole; + Units = Enum.GetValues(typeof(MolarMassUnit)).Cast<MolarMassUnit>().ToArray(); + Zero = new MolarMass(0, BaseUnit); + Info = new QuantityInfo<MolarMassUnit>("MolarMass", + new UnitInfo<MolarMassUnit>[] + { + new UnitInfo<MolarMassUnit>(MolarMassUnit.CentigramPerMole, "CentigramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.DecagramPerMole, "DecagramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.DecigramPerMole, "DecigramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.GramPerMole, "GramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.HectogramPerMole, "HectogramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.KilogramPerMole, "KilogramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.KilopoundPerMole, "KilopoundsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.MegapoundPerMole, "MegapoundsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.MicrogramPerMole, "MicrogramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.MilligramPerMole, "MilligramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.NanogramPerMole, "NanogramsPerMole", BaseUnits.Undefined), + new UnitInfo<MolarMassUnit>(MolarMassUnit.PoundPerMole, "PoundsPerMole", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public MolarMass(double value, MolarMassUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="MolarMass" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MolarMassUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. + /// </summary> + public static MolarMassUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the MolarMass quantity. + /// </summary> + public static MolarMassUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. + /// </summary> + public static MolarMass Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static MolarMass AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MolarMassUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => MolarMass.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.CentigramPerMole"/> + /// </summary> + public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.DecagramPerMole"/> + /// </summary> + public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.DecigramPerMole"/> + /// </summary> + public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.GramPerMole"/> + /// </summary> + public double GramsPerMole => As(MolarMassUnit.GramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.HectogramPerMole"/> + /// </summary> + public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.KilogramPerMole"/> + /// </summary> + public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.KilopoundPerMole"/> + /// </summary> + public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.MegapoundPerMole"/> + /// </summary> + public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.MicrogramPerMole"/> + /// </summary> + public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.MilligramPerMole"/> + /// </summary> + public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.NanogramPerMole"/> + /// </summary> + public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarMassUnit.PoundPerMole"/> + /// </summary> + public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MolarMassUnit -> BaseUnit + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.CentigramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.DecagramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.DecigramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.GramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.HectogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilopoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.MegapoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.MicrogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.MilligramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.NanogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.PoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity); + + // Register in unit converter: BaseUnit -> MolarMassUnit + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.CentigramPerMole, quantity => quantity.ToUnit(MolarMassUnit.CentigramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecagramPerMole, quantity => quantity.ToUnit(MolarMassUnit.DecagramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecigramPerMole, quantity => quantity.ToUnit(MolarMassUnit.DecigramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.GramPerMole, quantity => quantity.ToUnit(MolarMassUnit.GramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.HectogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.HectogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilopoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilopoundPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.MegapoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.MegapoundPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.MicrogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.MicrogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.MilligramPerMole, quantity => quantity.ToUnit(MolarMassUnit.MilligramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.NanogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.NanogramPerMole)); + unitConverter.SetConversionFunction<MolarMass>(MolarMassUnit.KilogramPerMole, MolarMassUnit.PoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.PoundPerMole)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.CentigramPerMole, new CultureInfo("en-US"), false, true, new string[]{"cg/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.CentigramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"сг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.DecagramPerMole, new CultureInfo("en-US"), false, true, new string[]{"dag/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.DecagramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"даг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.DecigramPerMole, new CultureInfo("en-US"), false, true, new string[]{"dg/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.DecigramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"дг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.GramPerMole, new CultureInfo("en-US"), false, true, new string[]{"g/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.GramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"г/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.HectogramPerMole, new CultureInfo("en-US"), false, true, new string[]{"hg/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.HectogramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"гг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.KilogramPerMole, new CultureInfo("en-US"), false, true, new string[]{"kg/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.KilogramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"кг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.KilopoundPerMole, new CultureInfo("en-US"), false, true, new string[]{"klb/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.KilopoundPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"кфунт/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.MegapoundPerMole, new CultureInfo("en-US"), false, true, new string[]{"Mlb/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.MegapoundPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"Мфунт/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.MicrogramPerMole, new CultureInfo("en-US"), false, true, new string[]{"µg/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.MicrogramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"мкг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.MilligramPerMole, new CultureInfo("en-US"), false, true, new string[]{"mg/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.MilligramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"мг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.NanogramPerMole, new CultureInfo("en-US"), false, true, new string[]{"ng/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.NanogramPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"нг/моль"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.PoundPerMole, new CultureInfo("en-US"), false, true, new string[]{"lb/mol"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarMassUnit.PoundPerMole, new CultureInfo("ru-RU"), false, true, new string[]{"фунт/моль"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MolarMassUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MolarMassUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.CentigramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) + { + double value = (double) centigramspermole; + return new MolarMass(value, MolarMassUnit.CentigramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.DecagramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) + { + double value = (double) decagramspermole; + return new MolarMass(value, MolarMassUnit.DecagramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.DecigramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) + { + double value = (double) decigramspermole; + return new MolarMass(value, MolarMassUnit.DecigramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.GramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromGramsPerMole(QuantityValue gramspermole) + { + double value = (double) gramspermole; + return new MolarMass(value, MolarMassUnit.GramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.HectogramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) + { + double value = (double) hectogramspermole; + return new MolarMass(value, MolarMassUnit.HectogramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.KilogramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) + { + double value = (double) kilogramspermole; + return new MolarMass(value, MolarMassUnit.KilogramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.KilopoundPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) + { + double value = (double) kilopoundspermole; + return new MolarMass(value, MolarMassUnit.KilopoundPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.MegapoundPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) + { + double value = (double) megapoundspermole; + return new MolarMass(value, MolarMassUnit.MegapoundPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.MicrogramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) + { + double value = (double) microgramspermole; + return new MolarMass(value, MolarMassUnit.MicrogramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.MilligramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) + { + double value = (double) milligramspermole; + return new MolarMass(value, MolarMassUnit.MilligramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.NanogramPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) + { + double value = (double) nanogramspermole; + return new MolarMass(value, MolarMassUnit.NanogramPerMole); + } + + /// <summary> + /// Creates a <see cref="MolarMass"/> from <see cref="MolarMassUnit.PoundPerMole"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) + { + double value = (double) poundspermole; + return new MolarMass(value, MolarMassUnit.PoundPerMole); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MolarMassUnit" /> to <see cref="MolarMass" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>MolarMass unit value.</returns> + public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) + { + return new MolarMass((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static MolarMass Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static MolarMass Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<MolarMass, MolarMassUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out MolarMass result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out MolarMass result) + { + return QuantityParser.Default.TryParse<MolarMass, MolarMassUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarMassUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarMassUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MolarMassUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MolarMassUnit)"/> + public static bool TryParseUnit(string str, out MolarMassUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarMassUnit unit) + { + return UnitParser.Default.TryParse<MolarMassUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static MolarMass operator -(MolarMass right) + { + return new MolarMass(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="MolarMass"/> from adding two <see cref="MolarMass"/>.</summary> + public static MolarMass operator +(MolarMass left, MolarMass right) + { + return new MolarMass(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MolarMass"/> from subtracting two <see cref="MolarMass"/>.</summary> + public static MolarMass operator -(MolarMass left, MolarMass right) + { + return new MolarMass(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="MolarMass"/> from multiplying value and <see cref="MolarMass"/>.</summary> + public static MolarMass operator *(double left, MolarMass right) + { + return new MolarMass(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="MolarMass"/> from multiplying value and <see cref="MolarMass"/>.</summary> + public static MolarMass operator *(MolarMass left, double right) + { + return new MolarMass(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="MolarMass"/> from dividing <see cref="MolarMass"/> by value.</summary> + public static MolarMass operator /(MolarMass left, double right) + { + return new MolarMass(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="MolarMass"/> by <see cref="MolarMass"/>.</summary> + public static double operator /(MolarMass left, MolarMass right) + { + return left.KilogramsPerMole / right.KilogramsPerMole; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(MolarMass left, MolarMass right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(MolarMass left, MolarMass right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(MolarMass left, MolarMass right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(MolarMass left, MolarMass right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="MolarMass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarMass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(MolarMass left, MolarMass right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="MolarMass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarMass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(MolarMass left, MolarMass right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MolarMass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarMass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is MolarMass otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="MolarMass"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(MolarMass, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(MolarMass other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="MolarMass"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is MolarMass otherQuantity)) throw new ArgumentException("Expected type MolarMass.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="MolarMass"/> with another <see cref="MolarMass"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(MolarMass other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another MolarMass within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current MolarMass.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MolarMassUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MolarMassUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this MolarMass to another MolarMass with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A MolarMass with the specified unit.</returns> + public MolarMass ToUnit(MolarMassUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="MolarMass"/> to another <see cref="MolarMass"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A MolarMass with the specified unit.</returns> + public MolarMass ToUnit(MolarMassUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(MolarMass), Unit, typeof(MolarMass), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (MolarMass)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="MolarMass"/> to another <see cref="MolarMass"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="MolarMass"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MolarMassUnit unit, [NotNullWhen(true)] out MolarMass? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + MolarMass? convertedOrNull = (Unit, unit) switch + { + // MolarMassUnit -> BaseUnit + (MolarMassUnit.CentigramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-2d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.DecagramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e1d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.DecigramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-1d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.GramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass(_value / 1e3, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.HectogramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e2d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.KilopoundPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value * 0.45359237) * 1e3d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.MegapoundPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value * 0.45359237) * 1e6d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.MicrogramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-6d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.MilligramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-3d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.NanogramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-9d, MolarMassUnit.KilogramPerMole), + (MolarMassUnit.PoundPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass(_value * 0.45359237, MolarMassUnit.KilogramPerMole), + + // BaseUnit -> MolarMassUnit + (MolarMassUnit.KilogramPerMole, MolarMassUnit.CentigramPerMole) => new MolarMass((_value * 1e3) / 1e-2d, MolarMassUnit.CentigramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.DecagramPerMole) => new MolarMass((_value * 1e3) / 1e1d, MolarMassUnit.DecagramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.DecigramPerMole) => new MolarMass((_value * 1e3) / 1e-1d, MolarMassUnit.DecigramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.GramPerMole) => new MolarMass(_value * 1e3, MolarMassUnit.GramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.HectogramPerMole) => new MolarMass((_value * 1e3) / 1e2d, MolarMassUnit.HectogramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.KilopoundPerMole) => new MolarMass((_value / 0.45359237) / 1e3d, MolarMassUnit.KilopoundPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.MegapoundPerMole) => new MolarMass((_value / 0.45359237) / 1e6d, MolarMassUnit.MegapoundPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.MicrogramPerMole) => new MolarMass((_value * 1e3) / 1e-6d, MolarMassUnit.MicrogramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.MilligramPerMole) => new MolarMass((_value * 1e3) / 1e-3d, MolarMassUnit.MilligramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.NanogramPerMole) => new MolarMass((_value * 1e3) / 1e-9d, MolarMassUnit.NanogramPerMole), + (MolarMassUnit.KilogramPerMole, MolarMassUnit.PoundPerMole) => new MolarMass(_value / 0.45359237, MolarMassUnit.PoundPerMole), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MolarMassUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MolarMassUnit> IQuantity<MolarMassUnit>.ToUnit(MolarMassUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MolarMassUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarMass)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarMass)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(MolarMass)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(MolarMass)) + return this; + else if (conversionType == typeof(MolarMassUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return MolarMass.Info; + else if (conversionType == typeof(BaseDimensions)) + return MolarMass.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(MolarMass)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMassUnit.g.cs b/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMassUnit.g.cs new file mode 100644 index 0000000000..417075c855 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/MolarMass/MolarMassUnit.g.cs @@ -0,0 +1,43 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MolarMassUnit + { + CentigramPerMole = 1, + DecagramPerMole = 2, + DecigramPerMole = 3, + GramPerMole = 4, + HectogramPerMole = 5, + KilogramPerMole = 6, + KilopoundPerMole = 7, + MegapoundPerMole = 8, + MicrogramPerMole = 9, + MilligramPerMole = 10, + NanogramPerMole = 11, + PoundPerMole = 12, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Molarity/Molarity.csproj b/UnitsNet.Modular/GeneratedCode/Molarity/Molarity.csproj new file mode 100644 index 0000000000..1828c19de6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Molarity/Molarity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Molarity</Title> + <Description>Adds Molarity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>molarity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{0d21f127-8c25-9b3a-9612-ce2eea6e7ac1}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Molarity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Molarity/Molarity.g.cs b/UnitsNet.Modular/GeneratedCode/Molarity/Molarity.g.cs new file mode 100644 index 0000000000..fd5502c5dd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Molarity/Molarity.g.cs @@ -0,0 +1,1009 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Molar_concentration + /// </remarks> + [DataContract] + public readonly partial struct Molarity : IArithmeticQuantity<Molarity, MolarityUnit, double>, IEquatable<Molarity>, IComparable, IComparable<Molarity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly MolarityUnit? _unit; + + static Molarity() + { + BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); + BaseUnit = MolarityUnit.MolePerCubicMeter; + Units = Enum.GetValues(typeof(MolarityUnit)).Cast<MolarityUnit>().ToArray(); + Zero = new Molarity(0, BaseUnit); + Info = new QuantityInfo<MolarityUnit>("Molarity", + new UnitInfo<MolarityUnit>[] + { + new UnitInfo<MolarityUnit>(MolarityUnit.CentimolePerLiter, "CentimolesPerLiter", BaseUnits.Undefined), + new UnitInfo<MolarityUnit>(MolarityUnit.DecimolePerLiter, "DecimolesPerLiter", BaseUnits.Undefined), + new UnitInfo<MolarityUnit>(MolarityUnit.FemtomolePerLiter, "FemtomolesPerLiter", BaseUnits.Undefined), + new UnitInfo<MolarityUnit>(MolarityUnit.MicromolePerLiter, "MicromolesPerLiter", BaseUnits.Undefined), + new UnitInfo<MolarityUnit>(MolarityUnit.MillimolePerLiter, "MillimolesPerLiter", BaseUnits.Undefined), + new UnitInfo<MolarityUnit>(MolarityUnit.MolePerCubicMeter, "MolesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, amount: AmountOfSubstanceUnit.Mole)), + new UnitInfo<MolarityUnit>(MolarityUnit.MolePerLiter, "MolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Mole)), + new UnitInfo<MolarityUnit>(MolarityUnit.NanomolePerLiter, "NanomolesPerLiter", BaseUnits.Undefined), + new UnitInfo<MolarityUnit>(MolarityUnit.PicomolePerLiter, "PicomolesPerLiter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Molarity(double value, MolarityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Molarity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<MolarityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Molarity, which is MolePerCubicMeter. All conversions go via this value. + /// </summary> + public static MolarityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Molarity quantity. + /// </summary> + public static MolarityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit MolePerCubicMeter. + /// </summary> + public static Molarity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Molarity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<MolarityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Molarity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.CentimolePerLiter"/> + /// </summary> + public double CentimolesPerLiter => As(MolarityUnit.CentimolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.DecimolePerLiter"/> + /// </summary> + public double DecimolesPerLiter => As(MolarityUnit.DecimolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.FemtomolePerLiter"/> + /// </summary> + public double FemtomolesPerLiter => As(MolarityUnit.FemtomolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.MicromolePerLiter"/> + /// </summary> + public double MicromolesPerLiter => As(MolarityUnit.MicromolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.MillimolePerLiter"/> + /// </summary> + public double MillimolesPerLiter => As(MolarityUnit.MillimolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.MolePerCubicMeter"/> + /// </summary> + public double MolesPerCubicMeter => As(MolarityUnit.MolePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.MolePerLiter"/> + /// </summary> + public double MolesPerLiter => As(MolarityUnit.MolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.NanomolePerLiter"/> + /// </summary> + public double NanomolesPerLiter => As(MolarityUnit.NanomolePerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="MolarityUnit.PicomolePerLiter"/> + /// </summary> + public double PicomolesPerLiter => As(MolarityUnit.PicomolePerLiter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: MolarityUnit -> BaseUnit + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.CentimolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.DecimolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.FemtomolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MicromolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MillimolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.NanomolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.PicomolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.MolePerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> MolarityUnit + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.CentimolePerLiter, quantity => quantity.ToUnit(MolarityUnit.CentimolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.DecimolePerLiter, quantity => quantity.ToUnit(MolarityUnit.DecimolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.FemtomolePerLiter, quantity => quantity.ToUnit(MolarityUnit.FemtomolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.MicromolePerLiter, quantity => quantity.ToUnit(MolarityUnit.MicromolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.MillimolePerLiter, quantity => quantity.ToUnit(MolarityUnit.MillimolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.MolePerLiter, quantity => quantity.ToUnit(MolarityUnit.MolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.NanomolePerLiter, quantity => quantity.ToUnit(MolarityUnit.NanomolePerLiter)); + unitConverter.SetConversionFunction<Molarity>(MolarityUnit.MolePerCubicMeter, MolarityUnit.PicomolePerLiter, quantity => quantity.ToUnit(MolarityUnit.PicomolePerLiter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.CentimolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"cmol/L", "cM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.DecimolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"dmol/L", "dM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.FemtomolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"fmol/L", "fM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MicromolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"µmol/L", "µM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MillimolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"mmol/L", "mM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MolePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"mol/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.MolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"mol/L", "M"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.NanomolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"nmol/L", "nM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(MolarityUnit.PicomolePerLiter, new CultureInfo("en-US"), false, true, new string[]{"pmol/L", "pM"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(MolarityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(MolarityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.CentimolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) + { + double value = (double) centimolesperliter; + return new Molarity(value, MolarityUnit.CentimolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.DecimolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) + { + double value = (double) decimolesperliter; + return new Molarity(value, MolarityUnit.DecimolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.FemtomolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromFemtomolesPerLiter(QuantityValue femtomolesperliter) + { + double value = (double) femtomolesperliter; + return new Molarity(value, MolarityUnit.FemtomolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.MicromolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) + { + double value = (double) micromolesperliter; + return new Molarity(value, MolarityUnit.MicromolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.MillimolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) + { + double value = (double) millimolesperliter; + return new Molarity(value, MolarityUnit.MillimolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.MolePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) + { + double value = (double) molespercubicmeter; + return new Molarity(value, MolarityUnit.MolePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.MolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromMolesPerLiter(QuantityValue molesperliter) + { + double value = (double) molesperliter; + return new Molarity(value, MolarityUnit.MolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.NanomolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) + { + double value = (double) nanomolesperliter; + return new Molarity(value, MolarityUnit.NanomolePerLiter); + } + + /// <summary> + /// Creates a <see cref="Molarity"/> from <see cref="MolarityUnit.PicomolePerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) + { + double value = (double) picomolesperliter; + return new Molarity(value, MolarityUnit.PicomolePerLiter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="MolarityUnit" /> to <see cref="Molarity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Molarity unit value.</returns> + public static Molarity From(QuantityValue value, MolarityUnit fromUnit) + { + return new Molarity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Molarity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Molarity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Molarity, MolarityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Molarity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Molarity result) + { + return QuantityParser.Default.TryParse<Molarity, MolarityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static MolarityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<MolarityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.MolarityUnit)"/> + public static bool TryParseUnit(string str, out MolarityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out MolarityUnit unit) + { + return UnitParser.Default.TryParse<MolarityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Molarity operator -(Molarity right) + { + return new Molarity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Molarity"/> from adding two <see cref="Molarity"/>.</summary> + public static Molarity operator +(Molarity left, Molarity right) + { + return new Molarity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Molarity"/> from subtracting two <see cref="Molarity"/>.</summary> + public static Molarity operator -(Molarity left, Molarity right) + { + return new Molarity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Molarity"/> from multiplying value and <see cref="Molarity"/>.</summary> + public static Molarity operator *(double left, Molarity right) + { + return new Molarity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Molarity"/> from multiplying value and <see cref="Molarity"/>.</summary> + public static Molarity operator *(Molarity left, double right) + { + return new Molarity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Molarity"/> from dividing <see cref="Molarity"/> by value.</summary> + public static Molarity operator /(Molarity left, double right) + { + return new Molarity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Molarity"/> by <see cref="Molarity"/>.</summary> + public static double operator /(Molarity left, Molarity right) + { + return left.MolesPerCubicMeter / right.MolesPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Molarity left, Molarity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Molarity left, Molarity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Molarity left, Molarity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Molarity left, Molarity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Molarity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Molarity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Molarity left, Molarity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Molarity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Molarity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Molarity left, Molarity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Molarity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Molarity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Molarity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Molarity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Molarity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Molarity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Molarity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Molarity otherQuantity)) throw new ArgumentException("Expected type Molarity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Molarity"/> with another <see cref="Molarity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Molarity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Molarity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Molarity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(MolarityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is MolarityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Molarity to another Molarity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Molarity with the specified unit.</returns> + public Molarity ToUnit(MolarityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Molarity"/> to another <see cref="Molarity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Molarity with the specified unit.</returns> + public Molarity ToUnit(MolarityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Molarity), Unit, typeof(Molarity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Molarity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Molarity"/> to another <see cref="Molarity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Molarity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(MolarityUnit unit, [NotNullWhen(true)] out Molarity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Molarity? convertedOrNull = (Unit, unit) switch + { + // MolarityUnit -> BaseUnit + (MolarityUnit.CentimolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-2d, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.DecimolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-1d, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.FemtomolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-15d, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.MicromolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-6d, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.MillimolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-3d, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.MolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity(_value / 1e-3, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.NanomolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-9d, MolarityUnit.MolePerCubicMeter), + (MolarityUnit.PicomolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-12d, MolarityUnit.MolePerCubicMeter), + + // BaseUnit -> MolarityUnit + (MolarityUnit.MolePerCubicMeter, MolarityUnit.CentimolePerLiter) => new Molarity((_value * 1e-3) / 1e-2d, MolarityUnit.CentimolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.DecimolePerLiter) => new Molarity((_value * 1e-3) / 1e-1d, MolarityUnit.DecimolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.FemtomolePerLiter) => new Molarity((_value * 1e-3) / 1e-15d, MolarityUnit.FemtomolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.MicromolePerLiter) => new Molarity((_value * 1e-3) / 1e-6d, MolarityUnit.MicromolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.MillimolePerLiter) => new Molarity((_value * 1e-3) / 1e-3d, MolarityUnit.MillimolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.MolePerLiter) => new Molarity(_value * 1e-3, MolarityUnit.MolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.NanomolePerLiter) => new Molarity((_value * 1e-3) / 1e-9d, MolarityUnit.NanomolePerLiter), + (MolarityUnit.MolePerCubicMeter, MolarityUnit.PicomolePerLiter) => new Molarity((_value * 1e-3) / 1e-12d, MolarityUnit.PicomolePerLiter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is MolarityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<MolarityUnit> IQuantity<MolarityUnit>.ToUnit(MolarityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<MolarityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Molarity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Molarity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Molarity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Molarity)) + return this; + else if (conversionType == typeof(MolarityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Molarity.Info; + else if (conversionType == typeof(BaseDimensions)) + return Molarity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Molarity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Molarity/MolarityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Molarity/MolarityUnit.g.cs new file mode 100644 index 0000000000..3119352a47 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Molarity/MolarityUnit.g.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum MolarityUnit + { + CentimolePerLiter = 1, + DecimolePerLiter = 3, + FemtomolePerLiter = 5, + MicromolePerLiter = 6, + MillimolePerLiter = 8, + MolePerCubicMeter = 10, + MolePerLiter = 11, + NanomolePerLiter = 14, + PicomolePerLiter = 16, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Permeability/Permeability.csproj b/UnitsNet.Modular/GeneratedCode/Permeability/Permeability.csproj new file mode 100644 index 0000000000..e0bdb715b6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Permeability/Permeability.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Permeability</Title> + <Description>Adds Permeability units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>permeability unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{34a31e0b-15ec-829c-6f0b-74f5acfd97e2}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Permeability</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Permeability/Permeability.g.cs b/UnitsNet.Modular/GeneratedCode/Permeability/Permeability.g.cs new file mode 100644 index 0000000000..e67b4eeec8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Permeability/Permeability.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) + /// </remarks> + [DataContract] + public readonly partial struct Permeability : IArithmeticQuantity<Permeability, PermeabilityUnit, double>, IEquatable<Permeability>, IComparable, IComparable<Permeability>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PermeabilityUnit? _unit; + + static Permeability() + { + BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); + BaseUnit = PermeabilityUnit.HenryPerMeter; + Units = Enum.GetValues(typeof(PermeabilityUnit)).Cast<PermeabilityUnit>().ToArray(); + Zero = new Permeability(0, BaseUnit); + Info = new QuantityInfo<PermeabilityUnit>("Permeability", + new UnitInfo<PermeabilityUnit>[] + { + new UnitInfo<PermeabilityUnit>(PermeabilityUnit.HenryPerMeter, "HenriesPerMeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Permeability(double value, PermeabilityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Permeability" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PermeabilityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. + /// </summary> + public static PermeabilityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Permeability quantity. + /// </summary> + public static PermeabilityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. + /// </summary> + public static Permeability Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Permeability AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PermeabilityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Permeability.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PermeabilityUnit.HenryPerMeter"/> + /// </summary> + public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PermeabilityUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Permeability>(PermeabilityUnit.HenryPerMeter, PermeabilityUnit.HenryPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> PermeabilityUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PermeabilityUnit.HenryPerMeter, new CultureInfo("en-US"), false, true, new string[]{"H/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PermeabilityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PermeabilityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Permeability"/> from <see cref="PermeabilityUnit.HenryPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) + { + double value = (double) henriespermeter; + return new Permeability(value, PermeabilityUnit.HenryPerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PermeabilityUnit" /> to <see cref="Permeability" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Permeability unit value.</returns> + public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) + { + return new Permeability((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Permeability Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Permeability Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Permeability, PermeabilityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Permeability result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Permeability result) + { + return QuantityParser.Default.TryParse<Permeability, PermeabilityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PermeabilityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PermeabilityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PermeabilityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PermeabilityUnit)"/> + public static bool TryParseUnit(string str, out PermeabilityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PermeabilityUnit unit) + { + return UnitParser.Default.TryParse<PermeabilityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Permeability operator -(Permeability right) + { + return new Permeability(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Permeability"/> from adding two <see cref="Permeability"/>.</summary> + public static Permeability operator +(Permeability left, Permeability right) + { + return new Permeability(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Permeability"/> from subtracting two <see cref="Permeability"/>.</summary> + public static Permeability operator -(Permeability left, Permeability right) + { + return new Permeability(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Permeability"/> from multiplying value and <see cref="Permeability"/>.</summary> + public static Permeability operator *(double left, Permeability right) + { + return new Permeability(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Permeability"/> from multiplying value and <see cref="Permeability"/>.</summary> + public static Permeability operator *(Permeability left, double right) + { + return new Permeability(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Permeability"/> from dividing <see cref="Permeability"/> by value.</summary> + public static Permeability operator /(Permeability left, double right) + { + return new Permeability(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Permeability"/> by <see cref="Permeability"/>.</summary> + public static double operator /(Permeability left, Permeability right) + { + return left.HenriesPerMeter / right.HenriesPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Permeability left, Permeability right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Permeability left, Permeability right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Permeability left, Permeability right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Permeability left, Permeability right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Permeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Permeability left, Permeability right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Permeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Permeability left, Permeability right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Permeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Permeability otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Permeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Permeability other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Permeability"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Permeability otherQuantity)) throw new ArgumentException("Expected type Permeability.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Permeability"/> with another <see cref="Permeability"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Permeability other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Permeability within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Permeability.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PermeabilityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PermeabilityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Permeability to another Permeability with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Permeability with the specified unit.</returns> + public Permeability ToUnit(PermeabilityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Permeability"/> to another <see cref="Permeability"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Permeability with the specified unit.</returns> + public Permeability ToUnit(PermeabilityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Permeability), Unit, typeof(Permeability), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Permeability)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Permeability"/> to another <see cref="Permeability"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Permeability"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PermeabilityUnit unit, [NotNullWhen(true)] out Permeability? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Permeability? convertedOrNull = (Unit, unit) switch + { + // PermeabilityUnit -> BaseUnit + + // BaseUnit -> PermeabilityUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PermeabilityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PermeabilityUnit> IQuantity<PermeabilityUnit>.ToUnit(PermeabilityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PermeabilityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Permeability)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Permeability)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Permeability)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Permeability)) + return this; + else if (conversionType == typeof(PermeabilityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Permeability.Info; + else if (conversionType == typeof(BaseDimensions)) + return Permeability.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Permeability)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Permeability/PermeabilityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Permeability/PermeabilityUnit.g.cs new file mode 100644 index 0000000000..19860cb22a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Permeability/PermeabilityUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PermeabilityUnit + { + HenryPerMeter = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Permittivity/Permittivity.csproj b/UnitsNet.Modular/GeneratedCode/Permittivity/Permittivity.csproj new file mode 100644 index 0000000000..8f4908e2a2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Permittivity/Permittivity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Permittivity</Title> + <Description>Adds Permittivity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>permittivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{9b381685-8129-acba-66f0-7068fe43a6c3}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Permittivity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Permittivity/Permittivity.g.cs b/UnitsNet.Modular/GeneratedCode/Permittivity/Permittivity.g.cs new file mode 100644 index 0000000000..c47a19c668 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Permittivity/Permittivity.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Permittivity + /// </remarks> + [DataContract] + public readonly partial struct Permittivity : IArithmeticQuantity<Permittivity, PermittivityUnit, double>, IEquatable<Permittivity>, IComparable, IComparable<Permittivity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PermittivityUnit? _unit; + + static Permittivity() + { + BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); + BaseUnit = PermittivityUnit.FaradPerMeter; + Units = Enum.GetValues(typeof(PermittivityUnit)).Cast<PermittivityUnit>().ToArray(); + Zero = new Permittivity(0, BaseUnit); + Info = new QuantityInfo<PermittivityUnit>("Permittivity", + new UnitInfo<PermittivityUnit>[] + { + new UnitInfo<PermittivityUnit>(PermittivityUnit.FaradPerMeter, "FaradsPerMeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Permittivity(double value, PermittivityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Permittivity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PermittivityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. + /// </summary> + public static PermittivityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Permittivity quantity. + /// </summary> + public static PermittivityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. + /// </summary> + public static Permittivity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Permittivity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PermittivityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Permittivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PermittivityUnit.FaradPerMeter"/> + /// </summary> + public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PermittivityUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Permittivity>(PermittivityUnit.FaradPerMeter, PermittivityUnit.FaradPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> PermittivityUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PermittivityUnit.FaradPerMeter, new CultureInfo("en-US"), false, true, new string[]{"F/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PermittivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PermittivityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Permittivity"/> from <see cref="PermittivityUnit.FaradPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) + { + double value = (double) faradspermeter; + return new Permittivity(value, PermittivityUnit.FaradPerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PermittivityUnit" /> to <see cref="Permittivity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Permittivity unit value.</returns> + public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) + { + return new Permittivity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Permittivity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Permittivity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Permittivity, PermittivityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Permittivity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Permittivity result) + { + return QuantityParser.Default.TryParse<Permittivity, PermittivityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PermittivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PermittivityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PermittivityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PermittivityUnit)"/> + public static bool TryParseUnit(string str, out PermittivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PermittivityUnit unit) + { + return UnitParser.Default.TryParse<PermittivityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Permittivity operator -(Permittivity right) + { + return new Permittivity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Permittivity"/> from adding two <see cref="Permittivity"/>.</summary> + public static Permittivity operator +(Permittivity left, Permittivity right) + { + return new Permittivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Permittivity"/> from subtracting two <see cref="Permittivity"/>.</summary> + public static Permittivity operator -(Permittivity left, Permittivity right) + { + return new Permittivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Permittivity"/> from multiplying value and <see cref="Permittivity"/>.</summary> + public static Permittivity operator *(double left, Permittivity right) + { + return new Permittivity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Permittivity"/> from multiplying value and <see cref="Permittivity"/>.</summary> + public static Permittivity operator *(Permittivity left, double right) + { + return new Permittivity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Permittivity"/> from dividing <see cref="Permittivity"/> by value.</summary> + public static Permittivity operator /(Permittivity left, double right) + { + return new Permittivity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Permittivity"/> by <see cref="Permittivity"/>.</summary> + public static double operator /(Permittivity left, Permittivity right) + { + return left.FaradsPerMeter / right.FaradsPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Permittivity left, Permittivity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Permittivity left, Permittivity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Permittivity left, Permittivity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Permittivity left, Permittivity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Permittivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permittivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Permittivity left, Permittivity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Permittivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permittivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Permittivity left, Permittivity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Permittivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permittivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Permittivity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Permittivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Permittivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Permittivity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Permittivity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Permittivity otherQuantity)) throw new ArgumentException("Expected type Permittivity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Permittivity"/> with another <see cref="Permittivity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Permittivity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Permittivity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Permittivity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PermittivityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PermittivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Permittivity to another Permittivity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Permittivity with the specified unit.</returns> + public Permittivity ToUnit(PermittivityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Permittivity"/> to another <see cref="Permittivity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Permittivity with the specified unit.</returns> + public Permittivity ToUnit(PermittivityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Permittivity), Unit, typeof(Permittivity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Permittivity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Permittivity"/> to another <see cref="Permittivity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Permittivity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PermittivityUnit unit, [NotNullWhen(true)] out Permittivity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Permittivity? convertedOrNull = (Unit, unit) switch + { + // PermittivityUnit -> BaseUnit + + // BaseUnit -> PermittivityUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PermittivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PermittivityUnit> IQuantity<PermittivityUnit>.ToUnit(PermittivityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PermittivityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Permittivity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Permittivity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Permittivity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Permittivity)) + return this; + else if (conversionType == typeof(PermittivityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Permittivity.Info; + else if (conversionType == typeof(BaseDimensions)) + return Permittivity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Permittivity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Permittivity/PermittivityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Permittivity/PermittivityUnit.g.cs new file mode 100644 index 0000000000..77e869b6fe --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Permittivity/PermittivityUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PermittivityUnit + { + FaradPerMeter = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeability.csproj b/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeability.csproj new file mode 100644 index 0000000000..fae1a5f056 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeability.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET PorousMediumPermeability</Title> + <Description>Adds PorousMediumPermeability units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>porousmediumpermeability unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{493d1e8e-51c6-da82-9289-25bd26fab4a4}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.PorousMediumPermeability</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeability.g.cs b/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeability.g.cs new file mode 100644 index 0000000000..8a7e08f58e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeability.g.cs @@ -0,0 +1,925 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Permeability_(Earth_sciences) + /// </remarks> + [DataContract] + public readonly partial struct PorousMediumPermeability : IArithmeticQuantity<PorousMediumPermeability, PorousMediumPermeabilityUnit, double>, IEquatable<PorousMediumPermeability>, IComparable, IComparable<PorousMediumPermeability>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PorousMediumPermeabilityUnit? _unit; + + static PorousMediumPermeability() + { + BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + BaseUnit = PorousMediumPermeabilityUnit.SquareMeter; + Units = Enum.GetValues(typeof(PorousMediumPermeabilityUnit)).Cast<PorousMediumPermeabilityUnit>().ToArray(); + Zero = new PorousMediumPermeability(0, BaseUnit); + Info = new QuantityInfo<PorousMediumPermeabilityUnit>("PorousMediumPermeability", + new UnitInfo<PorousMediumPermeabilityUnit>[] + { + new UnitInfo<PorousMediumPermeabilityUnit>(PorousMediumPermeabilityUnit.Darcy, "Darcys", BaseUnits.Undefined), + new UnitInfo<PorousMediumPermeabilityUnit>(PorousMediumPermeabilityUnit.Microdarcy, "Microdarcys", BaseUnits.Undefined), + new UnitInfo<PorousMediumPermeabilityUnit>(PorousMediumPermeabilityUnit.Millidarcy, "Millidarcys", BaseUnits.Undefined), + new UnitInfo<PorousMediumPermeabilityUnit>(PorousMediumPermeabilityUnit.SquareCentimeter, "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter)), + new UnitInfo<PorousMediumPermeabilityUnit>(PorousMediumPermeabilityUnit.SquareMeter, "SquareMeters", new BaseUnits(length: LengthUnit.Meter)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public PorousMediumPermeability(double value, PorousMediumPermeabilityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="PorousMediumPermeability" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PorousMediumPermeabilityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of PorousMediumPermeability, which is SquareMeter. All conversions go via this value. + /// </summary> + public static PorousMediumPermeabilityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the PorousMediumPermeability quantity. + /// </summary> + public static PorousMediumPermeabilityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. + /// </summary> + public static PorousMediumPermeability Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static PorousMediumPermeability AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PorousMediumPermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PorousMediumPermeabilityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => PorousMediumPermeability.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PorousMediumPermeabilityUnit.Darcy"/> + /// </summary> + public double Darcys => As(PorousMediumPermeabilityUnit.Darcy); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PorousMediumPermeabilityUnit.Microdarcy"/> + /// </summary> + public double Microdarcys => As(PorousMediumPermeabilityUnit.Microdarcy); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PorousMediumPermeabilityUnit.Millidarcy"/> + /// </summary> + public double Millidarcys => As(PorousMediumPermeabilityUnit.Millidarcy); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PorousMediumPermeabilityUnit.SquareCentimeter"/> + /// </summary> + public double SquareCentimeters => As(PorousMediumPermeabilityUnit.SquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PorousMediumPermeabilityUnit.SquareMeter"/> + /// </summary> + public double SquareMeters => As(PorousMediumPermeabilityUnit.SquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PorousMediumPermeabilityUnit -> BaseUnit + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.Darcy, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.Microdarcy, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.Millidarcy, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.SquareCentimeter, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> PorousMediumPermeabilityUnit + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Darcy, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.Darcy)); + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Microdarcy, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.Microdarcy)); + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Millidarcy, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.Millidarcy)); + unitConverter.SetConversionFunction<PorousMediumPermeability>(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.SquareCentimeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareCentimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PorousMediumPermeabilityUnit.Darcy, new CultureInfo("en-US"), false, true, new string[]{"D"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PorousMediumPermeabilityUnit.Microdarcy, new CultureInfo("en-US"), false, true, new string[]{"µD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PorousMediumPermeabilityUnit.Millidarcy, new CultureInfo("en-US"), false, true, new string[]{"mD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PorousMediumPermeabilityUnit.SquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PorousMediumPermeabilityUnit.SquareMeter, new CultureInfo("en-US"), false, true, new string[]{"m²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PorousMediumPermeabilityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PorousMediumPermeabilityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="PorousMediumPermeability"/> from <see cref="PorousMediumPermeabilityUnit.Darcy"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PorousMediumPermeability FromDarcys(QuantityValue darcys) + { + double value = (double) darcys; + return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Darcy); + } + + /// <summary> + /// Creates a <see cref="PorousMediumPermeability"/> from <see cref="PorousMediumPermeabilityUnit.Microdarcy"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PorousMediumPermeability FromMicrodarcys(QuantityValue microdarcys) + { + double value = (double) microdarcys; + return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Microdarcy); + } + + /// <summary> + /// Creates a <see cref="PorousMediumPermeability"/> from <see cref="PorousMediumPermeabilityUnit.Millidarcy"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PorousMediumPermeability FromMillidarcys(QuantityValue millidarcys) + { + double value = (double) millidarcys; + return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Millidarcy); + } + + /// <summary> + /// Creates a <see cref="PorousMediumPermeability"/> from <see cref="PorousMediumPermeabilityUnit.SquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PorousMediumPermeability FromSquareCentimeters(QuantityValue squarecentimeters) + { + double value = (double) squarecentimeters; + return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="PorousMediumPermeability"/> from <see cref="PorousMediumPermeabilityUnit.SquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PorousMediumPermeability FromSquareMeters(QuantityValue squaremeters) + { + double value = (double) squaremeters; + return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PorousMediumPermeabilityUnit" /> to <see cref="PorousMediumPermeability" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>PorousMediumPermeability unit value.</returns> + public static PorousMediumPermeability From(QuantityValue value, PorousMediumPermeabilityUnit fromUnit) + { + return new PorousMediumPermeability((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static PorousMediumPermeability Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static PorousMediumPermeability Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<PorousMediumPermeability, PorousMediumPermeabilityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out PorousMediumPermeability result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out PorousMediumPermeability result) + { + return QuantityParser.Default.TryParse<PorousMediumPermeability, PorousMediumPermeabilityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PorousMediumPermeabilityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PorousMediumPermeabilityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PorousMediumPermeabilityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PorousMediumPermeabilityUnit)"/> + public static bool TryParseUnit(string str, out PorousMediumPermeabilityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PorousMediumPermeabilityUnit unit) + { + return UnitParser.Default.TryParse<PorousMediumPermeabilityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static PorousMediumPermeability operator -(PorousMediumPermeability right) + { + return new PorousMediumPermeability(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="PorousMediumPermeability"/> from adding two <see cref="PorousMediumPermeability"/>.</summary> + public static PorousMediumPermeability operator +(PorousMediumPermeability left, PorousMediumPermeability right) + { + return new PorousMediumPermeability(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="PorousMediumPermeability"/> from subtracting two <see cref="PorousMediumPermeability"/>.</summary> + public static PorousMediumPermeability operator -(PorousMediumPermeability left, PorousMediumPermeability right) + { + return new PorousMediumPermeability(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="PorousMediumPermeability"/> from multiplying value and <see cref="PorousMediumPermeability"/>.</summary> + public static PorousMediumPermeability operator *(double left, PorousMediumPermeability right) + { + return new PorousMediumPermeability(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="PorousMediumPermeability"/> from multiplying value and <see cref="PorousMediumPermeability"/>.</summary> + public static PorousMediumPermeability operator *(PorousMediumPermeability left, double right) + { + return new PorousMediumPermeability(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="PorousMediumPermeability"/> from dividing <see cref="PorousMediumPermeability"/> by value.</summary> + public static PorousMediumPermeability operator /(PorousMediumPermeability left, double right) + { + return new PorousMediumPermeability(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="PorousMediumPermeability"/> by <see cref="PorousMediumPermeability"/>.</summary> + public static double operator /(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.SquareMeters / right.SquareMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="PorousMediumPermeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PorousMediumPermeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(PorousMediumPermeability left, PorousMediumPermeability right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="PorousMediumPermeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PorousMediumPermeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(PorousMediumPermeability left, PorousMediumPermeability right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PorousMediumPermeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PorousMediumPermeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is PorousMediumPermeability otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PorousMediumPermeability"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PorousMediumPermeability, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(PorousMediumPermeability other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="PorousMediumPermeability"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is PorousMediumPermeability otherQuantity)) throw new ArgumentException("Expected type PorousMediumPermeability.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="PorousMediumPermeability"/> with another <see cref="PorousMediumPermeability"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(PorousMediumPermeability other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another PorousMediumPermeability within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(PorousMediumPermeability other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current PorousMediumPermeability.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PorousMediumPermeabilityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PorousMediumPermeabilityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this PorousMediumPermeability to another PorousMediumPermeability with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A PorousMediumPermeability with the specified unit.</returns> + public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="PorousMediumPermeability"/> to another <see cref="PorousMediumPermeability"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A PorousMediumPermeability with the specified unit.</returns> + public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(PorousMediumPermeability), Unit, typeof(PorousMediumPermeability), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (PorousMediumPermeability)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="PorousMediumPermeability"/> to another <see cref="PorousMediumPermeability"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="PorousMediumPermeability"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PorousMediumPermeabilityUnit unit, [NotNullWhen(true)] out PorousMediumPermeability? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + PorousMediumPermeability? convertedOrNull = (Unit, unit) switch + { + // PorousMediumPermeabilityUnit -> BaseUnit + (PorousMediumPermeabilityUnit.Darcy, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability(_value * 9.869233e-13, PorousMediumPermeabilityUnit.SquareMeter), + (PorousMediumPermeabilityUnit.Microdarcy, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability((_value * 9.869233e-13) * 1e-6d, PorousMediumPermeabilityUnit.SquareMeter), + (PorousMediumPermeabilityUnit.Millidarcy, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability((_value * 9.869233e-13) * 1e-3d, PorousMediumPermeabilityUnit.SquareMeter), + (PorousMediumPermeabilityUnit.SquareCentimeter, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability(_value * 1e-4, PorousMediumPermeabilityUnit.SquareMeter), + + // BaseUnit -> PorousMediumPermeabilityUnit + (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Darcy) => new PorousMediumPermeability(_value / 9.869233e-13, PorousMediumPermeabilityUnit.Darcy), + (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Microdarcy) => new PorousMediumPermeability((_value / 9.869233e-13) / 1e-6d, PorousMediumPermeabilityUnit.Microdarcy), + (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Millidarcy) => new PorousMediumPermeability((_value / 9.869233e-13) / 1e-3d, PorousMediumPermeabilityUnit.Millidarcy), + (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.SquareCentimeter) => new PorousMediumPermeability(_value / 1e-4, PorousMediumPermeabilityUnit.SquareCentimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PorousMediumPermeabilityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PorousMediumPermeabilityUnit> IQuantity<PorousMediumPermeabilityUnit>.ToUnit(PorousMediumPermeabilityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PorousMediumPermeabilityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(PorousMediumPermeability)) + return this; + else if (conversionType == typeof(PorousMediumPermeabilityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return PorousMediumPermeability.Info; + else if (conversionType == typeof(BaseDimensions)) + return PorousMediumPermeability.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeabilityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeabilityUnit.g.cs new file mode 100644 index 0000000000..9b57db7199 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PorousMediumPermeability/PorousMediumPermeabilityUnit.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PorousMediumPermeabilityUnit + { + Darcy = 1, + Microdarcy = 2, + Millidarcy = 3, + SquareCentimeter = 4, + SquareMeter = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Power/Power.csproj b/UnitsNet.Modular/GeneratedCode/Power/Power.csproj new file mode 100644 index 0000000000..67c27b25c1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Power/Power.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Power</Title> + <Description>Adds Power units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>power unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{56968e84-6b7d-d548-4c0b-53017bd6123c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Power</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Power/Power.g.cs b/UnitsNet.Modular/GeneratedCode/Power/Power.g.cs new file mode 100644 index 0000000000..e262fc0129 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Power/Power.g.cs @@ -0,0 +1,1371 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. + /// </summary> + [DataContract] + public readonly partial struct Power : IArithmeticQuantity<Power, PowerUnit, decimal>, IDecimalQuantity, IEquatable<Power>, IComparable, IComparable<Power>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly decimal _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PowerUnit? _unit; + + static Power() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + BaseUnit = PowerUnit.Watt; + Units = Enum.GetValues(typeof(PowerUnit)).Cast<PowerUnit>().ToArray(); + Zero = new Power(0, BaseUnit); + Info = new QuantityInfo<PowerUnit>("Power", + new UnitInfo<PowerUnit>[] + { + new UnitInfo<PowerUnit>(PowerUnit.BoilerHorsepower, "BoilerHorsepower", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.BritishThermalUnitPerHour, "BritishThermalUnitsPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Decawatt, "Decawatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Deciwatt, "Deciwatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.ElectricalHorsepower, "ElectricalHorsepower", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Femtowatt, "Femtowatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.GigajoulePerHour, "GigajoulesPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Gigawatt, "Gigawatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.HydraulicHorsepower, "HydraulicHorsepower", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.JoulePerHour, "JoulesPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.KilobritishThermalUnitPerHour, "KilobritishThermalUnitsPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.KilojoulePerHour, "KilojoulesPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Kilowatt, "Kilowatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.MechanicalHorsepower, "MechanicalHorsepower", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.MegabritishThermalUnitPerHour, "MegabritishThermalUnitsPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.MegajoulePerHour, "MegajoulesPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Megawatt, "Megawatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.MetricHorsepower, "MetricHorsepower", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Microwatt, "Microwatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.MillijoulePerHour, "MillijoulesPerHour", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Milliwatt, "Milliwatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Nanowatt, "Nanowatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Petawatt, "Petawatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Picowatt, "Picowatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Terawatt, "Terawatts", BaseUnits.Undefined), + new UnitInfo<PowerUnit>(PowerUnit.Watt, "Watts", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Power(decimal value, PowerUnit unit) + { + _value = value; + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Power" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PowerUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Power, which is Watt. All conversions go via this value. + /// </summary> + public static PowerUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Power quantity. + /// </summary> + public static PowerUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Watt. + /// </summary> + public static Power Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Power AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public decimal Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + /// <inheritdoc cref="IDecimalQuantity.Value"/> + decimal IDecimalQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PowerUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Power.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.BoilerHorsepower"/> + /// </summary> + public decimal BoilerHorsepower => As(PowerUnit.BoilerHorsepower); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.BritishThermalUnitPerHour"/> + /// </summary> + public decimal BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Decawatt"/> + /// </summary> + public decimal Decawatts => As(PowerUnit.Decawatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Deciwatt"/> + /// </summary> + public decimal Deciwatts => As(PowerUnit.Deciwatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.ElectricalHorsepower"/> + /// </summary> + public decimal ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Femtowatt"/> + /// </summary> + public decimal Femtowatts => As(PowerUnit.Femtowatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.GigajoulePerHour"/> + /// </summary> + public decimal GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Gigawatt"/> + /// </summary> + public decimal Gigawatts => As(PowerUnit.Gigawatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.HydraulicHorsepower"/> + /// </summary> + public decimal HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.JoulePerHour"/> + /// </summary> + public decimal JoulesPerHour => As(PowerUnit.JoulePerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.KilobritishThermalUnitPerHour"/> + /// </summary> + public decimal KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.KilojoulePerHour"/> + /// </summary> + public decimal KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Kilowatt"/> + /// </summary> + public decimal Kilowatts => As(PowerUnit.Kilowatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.MechanicalHorsepower"/> + /// </summary> + public decimal MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.MegabritishThermalUnitPerHour"/> + /// </summary> + public decimal MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.MegajoulePerHour"/> + /// </summary> + public decimal MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Megawatt"/> + /// </summary> + public decimal Megawatts => As(PowerUnit.Megawatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.MetricHorsepower"/> + /// </summary> + public decimal MetricHorsepower => As(PowerUnit.MetricHorsepower); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Microwatt"/> + /// </summary> + public decimal Microwatts => As(PowerUnit.Microwatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.MillijoulePerHour"/> + /// </summary> + public decimal MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Milliwatt"/> + /// </summary> + public decimal Milliwatts => As(PowerUnit.Milliwatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Nanowatt"/> + /// </summary> + public decimal Nanowatts => As(PowerUnit.Nanowatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Petawatt"/> + /// </summary> + public decimal Petawatts => As(PowerUnit.Petawatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Picowatt"/> + /// </summary> + public decimal Picowatts => As(PowerUnit.Picowatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Terawatt"/> + /// </summary> + public decimal Terawatts => As(PowerUnit.Terawatt); + + /// <summary> + /// Gets a <see cref="decimal"/> value of this quantity converted into <see cref="PowerUnit.Watt"/> + /// </summary> + public decimal Watts => As(PowerUnit.Watt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PowerUnit -> BaseUnit + unitConverter.SetConversionFunction<Power>(PowerUnit.BoilerHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Decawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Deciwatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.ElectricalHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Femtowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.GigajoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Gigawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.HydraulicHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.JoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.KilobritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.KilojoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Kilowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.MechanicalHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.MegabritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.MegajoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Megawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.MetricHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Microwatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.MillijoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Milliwatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Nanowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Petawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Picowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Terawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Watt, quantity => quantity); + + // Register in unit converter: BaseUnit -> PowerUnit + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.BoilerHorsepower, quantity => quantity.ToUnit(PowerUnit.BoilerHorsepower)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.BritishThermalUnitPerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Decawatt, quantity => quantity.ToUnit(PowerUnit.Decawatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Deciwatt, quantity => quantity.ToUnit(PowerUnit.Deciwatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.ElectricalHorsepower, quantity => quantity.ToUnit(PowerUnit.ElectricalHorsepower)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Femtowatt, quantity => quantity.ToUnit(PowerUnit.Femtowatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.GigajoulePerHour, quantity => quantity.ToUnit(PowerUnit.GigajoulePerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Gigawatt, quantity => quantity.ToUnit(PowerUnit.Gigawatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.HydraulicHorsepower, quantity => quantity.ToUnit(PowerUnit.HydraulicHorsepower)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.JoulePerHour, quantity => quantity.ToUnit(PowerUnit.JoulePerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.KilobritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.KilobritishThermalUnitPerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.KilojoulePerHour, quantity => quantity.ToUnit(PowerUnit.KilojoulePerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Kilowatt, quantity => quantity.ToUnit(PowerUnit.Kilowatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.MechanicalHorsepower, quantity => quantity.ToUnit(PowerUnit.MechanicalHorsepower)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.MegabritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.MegabritishThermalUnitPerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.MegajoulePerHour, quantity => quantity.ToUnit(PowerUnit.MegajoulePerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Megawatt, quantity => quantity.ToUnit(PowerUnit.Megawatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.MetricHorsepower, quantity => quantity.ToUnit(PowerUnit.MetricHorsepower)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Microwatt, quantity => quantity.ToUnit(PowerUnit.Microwatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.MillijoulePerHour, quantity => quantity.ToUnit(PowerUnit.MillijoulePerHour)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Milliwatt, quantity => quantity.ToUnit(PowerUnit.Milliwatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Nanowatt, quantity => quantity.ToUnit(PowerUnit.Nanowatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Petawatt, quantity => quantity.ToUnit(PowerUnit.Petawatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Picowatt, quantity => quantity.ToUnit(PowerUnit.Picowatt)); + unitConverter.SetConversionFunction<Power>(PowerUnit.Watt, PowerUnit.Terawatt, quantity => quantity.ToUnit(PowerUnit.Terawatt)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.BoilerHorsepower, new CultureInfo("en-US"), false, true, new string[]{"hp(S)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.BritishThermalUnitPerHour, new CultureInfo("en-US"), false, true, new string[]{"Btu/h", "Btu/hr"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Decawatt, new CultureInfo("en-US"), false, true, new string[]{"daW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Deciwatt, new CultureInfo("en-US"), false, true, new string[]{"dW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.ElectricalHorsepower, new CultureInfo("en-US"), false, true, new string[]{"hp(E)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Femtowatt, new CultureInfo("en-US"), false, true, new string[]{"fW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.GigajoulePerHour, new CultureInfo("en-US"), false, true, new string[]{"GJ/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Gigawatt, new CultureInfo("en-US"), false, true, new string[]{"GW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.HydraulicHorsepower, new CultureInfo("en-US"), false, true, new string[]{"hp(H)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.JoulePerHour, new CultureInfo("en-US"), false, true, new string[]{"J/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.KilobritishThermalUnitPerHour, new CultureInfo("en-US"), false, true, new string[]{"kBtu/h", "kBtu/hr"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.KilojoulePerHour, new CultureInfo("en-US"), false, true, new string[]{"kJ/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Kilowatt, new CultureInfo("en-US"), false, true, new string[]{"kW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.MechanicalHorsepower, new CultureInfo("en-US"), false, true, new string[]{"hp(I)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.MegabritishThermalUnitPerHour, new CultureInfo("en-US"), false, true, new string[]{"MBtu/h", "MBtu/hr"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.MegajoulePerHour, new CultureInfo("en-US"), false, true, new string[]{"MJ/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Megawatt, new CultureInfo("en-US"), false, true, new string[]{"MW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.MetricHorsepower, new CultureInfo("en-US"), false, true, new string[]{"hp(M)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Microwatt, new CultureInfo("en-US"), false, true, new string[]{"µW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.MillijoulePerHour, new CultureInfo("en-US"), false, true, new string[]{"mJ/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Milliwatt, new CultureInfo("en-US"), false, true, new string[]{"mW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Nanowatt, new CultureInfo("en-US"), false, true, new string[]{"nW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Petawatt, new CultureInfo("en-US"), false, true, new string[]{"PW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Picowatt, new CultureInfo("en-US"), false, true, new string[]{"pW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Terawatt, new CultureInfo("en-US"), false, true, new string[]{"TW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerUnit.Watt, new CultureInfo("en-US"), false, true, new string[]{"W"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PowerUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PowerUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.BoilerHorsepower"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) + { + decimal value = (decimal) boilerhorsepower; + return new Power(value, PowerUnit.BoilerHorsepower); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.BritishThermalUnitPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) + { + decimal value = (decimal) britishthermalunitsperhour; + return new Power(value, PowerUnit.BritishThermalUnitPerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Decawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromDecawatts(QuantityValue decawatts) + { + decimal value = (decimal) decawatts; + return new Power(value, PowerUnit.Decawatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Deciwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromDeciwatts(QuantityValue deciwatts) + { + decimal value = (decimal) deciwatts; + return new Power(value, PowerUnit.Deciwatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.ElectricalHorsepower"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) + { + decimal value = (decimal) electricalhorsepower; + return new Power(value, PowerUnit.ElectricalHorsepower); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Femtowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromFemtowatts(QuantityValue femtowatts) + { + decimal value = (decimal) femtowatts; + return new Power(value, PowerUnit.Femtowatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.GigajoulePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromGigajoulesPerHour(QuantityValue gigajoulesperhour) + { + decimal value = (decimal) gigajoulesperhour; + return new Power(value, PowerUnit.GigajoulePerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Gigawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromGigawatts(QuantityValue gigawatts) + { + decimal value = (decimal) gigawatts; + return new Power(value, PowerUnit.Gigawatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.HydraulicHorsepower"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) + { + decimal value = (decimal) hydraulichorsepower; + return new Power(value, PowerUnit.HydraulicHorsepower); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.JoulePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromJoulesPerHour(QuantityValue joulesperhour) + { + decimal value = (decimal) joulesperhour; + return new Power(value, PowerUnit.JoulePerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.KilobritishThermalUnitPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) + { + decimal value = (decimal) kilobritishthermalunitsperhour; + return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.KilojoulePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromKilojoulesPerHour(QuantityValue kilojoulesperhour) + { + decimal value = (decimal) kilojoulesperhour; + return new Power(value, PowerUnit.KilojoulePerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Kilowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromKilowatts(QuantityValue kilowatts) + { + decimal value = (decimal) kilowatts; + return new Power(value, PowerUnit.Kilowatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.MechanicalHorsepower"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) + { + decimal value = (decimal) mechanicalhorsepower; + return new Power(value, PowerUnit.MechanicalHorsepower); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.MegabritishThermalUnitPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMegabritishThermalUnitsPerHour(QuantityValue megabritishthermalunitsperhour) + { + decimal value = (decimal) megabritishthermalunitsperhour; + return new Power(value, PowerUnit.MegabritishThermalUnitPerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.MegajoulePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMegajoulesPerHour(QuantityValue megajoulesperhour) + { + decimal value = (decimal) megajoulesperhour; + return new Power(value, PowerUnit.MegajoulePerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Megawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMegawatts(QuantityValue megawatts) + { + decimal value = (decimal) megawatts; + return new Power(value, PowerUnit.Megawatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.MetricHorsepower"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMetricHorsepower(QuantityValue metrichorsepower) + { + decimal value = (decimal) metrichorsepower; + return new Power(value, PowerUnit.MetricHorsepower); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Microwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMicrowatts(QuantityValue microwatts) + { + decimal value = (decimal) microwatts; + return new Power(value, PowerUnit.Microwatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.MillijoulePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMillijoulesPerHour(QuantityValue millijoulesperhour) + { + decimal value = (decimal) millijoulesperhour; + return new Power(value, PowerUnit.MillijoulePerHour); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Milliwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromMilliwatts(QuantityValue milliwatts) + { + decimal value = (decimal) milliwatts; + return new Power(value, PowerUnit.Milliwatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Nanowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromNanowatts(QuantityValue nanowatts) + { + decimal value = (decimal) nanowatts; + return new Power(value, PowerUnit.Nanowatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Petawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromPetawatts(QuantityValue petawatts) + { + decimal value = (decimal) petawatts; + return new Power(value, PowerUnit.Petawatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Picowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromPicowatts(QuantityValue picowatts) + { + decimal value = (decimal) picowatts; + return new Power(value, PowerUnit.Picowatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Terawatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromTerawatts(QuantityValue terawatts) + { + decimal value = (decimal) terawatts; + return new Power(value, PowerUnit.Terawatt); + } + + /// <summary> + /// Creates a <see cref="Power"/> from <see cref="PowerUnit.Watt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Power FromWatts(QuantityValue watts) + { + decimal value = (decimal) watts; + return new Power(value, PowerUnit.Watt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PowerUnit" /> to <see cref="Power" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Power unit value.</returns> + public static Power From(QuantityValue value, PowerUnit fromUnit) + { + return new Power((decimal)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Power Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Power Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Power, PowerUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Power result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Power result) + { + return QuantityParser.Default.TryParse<Power, PowerUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PowerUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PowerUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PowerUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PowerUnit)"/> + public static bool TryParseUnit(string str, out PowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PowerUnit unit) + { + return UnitParser.Default.TryParse<PowerUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Power operator -(Power right) + { + return new Power(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Power"/> from adding two <see cref="Power"/>.</summary> + public static Power operator +(Power left, Power right) + { + return new Power(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Power"/> from subtracting two <see cref="Power"/>.</summary> + public static Power operator -(Power left, Power right) + { + return new Power(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Power"/> from multiplying value and <see cref="Power"/>.</summary> + public static Power operator *(decimal left, Power right) + { + return new Power(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Power"/> from multiplying value and <see cref="Power"/>.</summary> + public static Power operator *(Power left, decimal right) + { + return new Power(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Power"/> from dividing <see cref="Power"/> by value.</summary> + public static Power operator /(Power left, decimal right) + { + return new Power(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Power"/> by <see cref="Power"/>.</summary> + public static decimal operator /(Power left, Power right) + { + return left.Watts / right.Watts; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Power left, Power right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Power left, Power right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Power left, Power right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Power left, Power right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Power"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Power, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Power left, Power right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Power"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Power, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Power left, Power right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Power"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Power, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Power otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Power"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Power, decimal, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, decimal, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Power other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Power"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Power otherQuantity)) throw new ArgumentException("Expected type Power.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Power"/> with another <see cref="Power"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Power other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Power within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using decimal internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Power other, decimal tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + decimal thisValue = this.Value; + decimal otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Power.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public decimal As(PowerUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + double IQuantity<PowerUnit>.As(PowerUnit unit) + { + return (double)As(unit); + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PowerUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Power to another Power with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Power with the specified unit.</returns> + public Power ToUnit(PowerUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Power"/> to another <see cref="Power"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Power with the specified unit.</returns> + public Power ToUnit(PowerUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Power), Unit, typeof(Power), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Power)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Power"/> to another <see cref="Power"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Power"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PowerUnit unit, [NotNullWhen(true)] out Power? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Power? convertedOrNull = (Unit, unit) switch + { + // PowerUnit -> BaseUnit + (PowerUnit.BoilerHorsepower, PowerUnit.Watt) => new Power(_value * 9812.5m, PowerUnit.Watt), + (PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt) => new Power(_value * 0.29307107017m, PowerUnit.Watt), + (PowerUnit.Decawatt, PowerUnit.Watt) => new Power((_value) * 1e1m, PowerUnit.Watt), + (PowerUnit.Deciwatt, PowerUnit.Watt) => new Power((_value) * 1e-1m, PowerUnit.Watt), + (PowerUnit.ElectricalHorsepower, PowerUnit.Watt) => new Power(_value * 746m, PowerUnit.Watt), + (PowerUnit.Femtowatt, PowerUnit.Watt) => new Power((_value) * 1e-15m, PowerUnit.Watt), + (PowerUnit.GigajoulePerHour, PowerUnit.Watt) => new Power((_value / 3600m) * 1e9m, PowerUnit.Watt), + (PowerUnit.Gigawatt, PowerUnit.Watt) => new Power((_value) * 1e9m, PowerUnit.Watt), + (PowerUnit.HydraulicHorsepower, PowerUnit.Watt) => new Power(_value * 745.69988145m, PowerUnit.Watt), + (PowerUnit.JoulePerHour, PowerUnit.Watt) => new Power(_value / 3600m, PowerUnit.Watt), + (PowerUnit.KilobritishThermalUnitPerHour, PowerUnit.Watt) => new Power((_value * 0.29307107017m) * 1e3m, PowerUnit.Watt), + (PowerUnit.KilojoulePerHour, PowerUnit.Watt) => new Power((_value / 3600m) * 1e3m, PowerUnit.Watt), + (PowerUnit.Kilowatt, PowerUnit.Watt) => new Power((_value) * 1e3m, PowerUnit.Watt), + (PowerUnit.MechanicalHorsepower, PowerUnit.Watt) => new Power(_value * 745.69m, PowerUnit.Watt), + (PowerUnit.MegabritishThermalUnitPerHour, PowerUnit.Watt) => new Power((_value * 0.29307107017m) * 1e6m, PowerUnit.Watt), + (PowerUnit.MegajoulePerHour, PowerUnit.Watt) => new Power((_value / 3600m) * 1e6m, PowerUnit.Watt), + (PowerUnit.Megawatt, PowerUnit.Watt) => new Power((_value) * 1e6m, PowerUnit.Watt), + (PowerUnit.MetricHorsepower, PowerUnit.Watt) => new Power(_value * 735.49875m, PowerUnit.Watt), + (PowerUnit.Microwatt, PowerUnit.Watt) => new Power((_value) * 1e-6m, PowerUnit.Watt), + (PowerUnit.MillijoulePerHour, PowerUnit.Watt) => new Power((_value / 3600m) * 1e-3m, PowerUnit.Watt), + (PowerUnit.Milliwatt, PowerUnit.Watt) => new Power((_value) * 1e-3m, PowerUnit.Watt), + (PowerUnit.Nanowatt, PowerUnit.Watt) => new Power((_value) * 1e-9m, PowerUnit.Watt), + (PowerUnit.Petawatt, PowerUnit.Watt) => new Power((_value) * 1e15m, PowerUnit.Watt), + (PowerUnit.Picowatt, PowerUnit.Watt) => new Power((_value) * 1e-12m, PowerUnit.Watt), + (PowerUnit.Terawatt, PowerUnit.Watt) => new Power((_value) * 1e12m, PowerUnit.Watt), + + // BaseUnit -> PowerUnit + (PowerUnit.Watt, PowerUnit.BoilerHorsepower) => new Power(_value / 9812.5m, PowerUnit.BoilerHorsepower), + (PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour) => new Power(_value / 0.29307107017m, PowerUnit.BritishThermalUnitPerHour), + (PowerUnit.Watt, PowerUnit.Decawatt) => new Power((_value) / 1e1m, PowerUnit.Decawatt), + (PowerUnit.Watt, PowerUnit.Deciwatt) => new Power((_value) / 1e-1m, PowerUnit.Deciwatt), + (PowerUnit.Watt, PowerUnit.ElectricalHorsepower) => new Power(_value / 746m, PowerUnit.ElectricalHorsepower), + (PowerUnit.Watt, PowerUnit.Femtowatt) => new Power((_value) / 1e-15m, PowerUnit.Femtowatt), + (PowerUnit.Watt, PowerUnit.GigajoulePerHour) => new Power((_value * 3600m) / 1e9m, PowerUnit.GigajoulePerHour), + (PowerUnit.Watt, PowerUnit.Gigawatt) => new Power((_value) / 1e9m, PowerUnit.Gigawatt), + (PowerUnit.Watt, PowerUnit.HydraulicHorsepower) => new Power(_value / 745.69988145m, PowerUnit.HydraulicHorsepower), + (PowerUnit.Watt, PowerUnit.JoulePerHour) => new Power(_value * 3600m, PowerUnit.JoulePerHour), + (PowerUnit.Watt, PowerUnit.KilobritishThermalUnitPerHour) => new Power((_value / 0.29307107017m) / 1e3m, PowerUnit.KilobritishThermalUnitPerHour), + (PowerUnit.Watt, PowerUnit.KilojoulePerHour) => new Power((_value * 3600m) / 1e3m, PowerUnit.KilojoulePerHour), + (PowerUnit.Watt, PowerUnit.Kilowatt) => new Power((_value) / 1e3m, PowerUnit.Kilowatt), + (PowerUnit.Watt, PowerUnit.MechanicalHorsepower) => new Power(_value / 745.69m, PowerUnit.MechanicalHorsepower), + (PowerUnit.Watt, PowerUnit.MegabritishThermalUnitPerHour) => new Power((_value / 0.29307107017m) / 1e6m, PowerUnit.MegabritishThermalUnitPerHour), + (PowerUnit.Watt, PowerUnit.MegajoulePerHour) => new Power((_value * 3600m) / 1e6m, PowerUnit.MegajoulePerHour), + (PowerUnit.Watt, PowerUnit.Megawatt) => new Power((_value) / 1e6m, PowerUnit.Megawatt), + (PowerUnit.Watt, PowerUnit.MetricHorsepower) => new Power(_value / 735.49875m, PowerUnit.MetricHorsepower), + (PowerUnit.Watt, PowerUnit.Microwatt) => new Power((_value) / 1e-6m, PowerUnit.Microwatt), + (PowerUnit.Watt, PowerUnit.MillijoulePerHour) => new Power((_value * 3600m) / 1e-3m, PowerUnit.MillijoulePerHour), + (PowerUnit.Watt, PowerUnit.Milliwatt) => new Power((_value) / 1e-3m, PowerUnit.Milliwatt), + (PowerUnit.Watt, PowerUnit.Nanowatt) => new Power((_value) / 1e-9m, PowerUnit.Nanowatt), + (PowerUnit.Watt, PowerUnit.Petawatt) => new Power((_value) / 1e15m, PowerUnit.Petawatt), + (PowerUnit.Watt, PowerUnit.Picowatt) => new Power((_value) / 1e-12m, PowerUnit.Picowatt), + (PowerUnit.Watt, PowerUnit.Terawatt) => new Power((_value) / 1e12m, PowerUnit.Terawatt), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PowerUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PowerUnit> IQuantity<PowerUnit>.ToUnit(PowerUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PowerUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Power)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Power)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Power)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Power)) + return this; + else if (conversionType == typeof(PowerUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Power.Info; + else if (conversionType == typeof(BaseDimensions)) + return Power.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Power)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Power/PowerUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Power/PowerUnit.g.cs new file mode 100644 index 0000000000..303f690f6e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Power/PowerUnit.g.cs @@ -0,0 +1,57 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PowerUnit + { + BoilerHorsepower = 1, + BritishThermalUnitPerHour = 2, + Decawatt = 3, + Deciwatt = 4, + ElectricalHorsepower = 5, + Femtowatt = 6, + GigajoulePerHour = 7, + Gigawatt = 8, + HydraulicHorsepower = 9, + JoulePerHour = 10, + KilobritishThermalUnitPerHour = 11, + KilojoulePerHour = 12, + Kilowatt = 13, + MechanicalHorsepower = 14, + MegabritishThermalUnitPerHour = 15, + MegajoulePerHour = 16, + Megawatt = 17, + MetricHorsepower = 18, + Microwatt = 19, + MillijoulePerHour = 20, + Milliwatt = 21, + Nanowatt = 22, + Petawatt = 23, + Picowatt = 24, + Terawatt = 25, + Watt = 26, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensity.csproj b/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensity.csproj new file mode 100644 index 0000000000..f0625c8249 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET PowerDensity</Title> + <Description>Adds PowerDensity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>powerdensity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5e741dd9-690a-de16-e7a1-85e6239aa70d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.PowerDensity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensity.g.cs b/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensity.g.cs new file mode 100644 index 0000000000..843c9d2858 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensity.g.cs @@ -0,0 +1,1741 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The amount of power in a volume. + /// </summary> + [DataContract] + public readonly partial struct PowerDensity : IArithmeticQuantity<PowerDensity, PowerDensityUnit, double>, IEquatable<PowerDensity>, IComparable, IComparable<PowerDensity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PowerDensityUnit? _unit; + + static PowerDensity() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + BaseUnit = PowerDensityUnit.WattPerCubicMeter; + Units = Enum.GetValues(typeof(PowerDensityUnit)).Cast<PowerDensityUnit>().ToArray(); + Zero = new PowerDensity(0, BaseUnit); + Info = new QuantityInfo<PowerDensityUnit>("PowerDensity", + new UnitInfo<PowerDensityUnit>[] + { + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DecawattPerCubicFoot, "DecawattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DecawattPerCubicInch, "DecawattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DecawattPerCubicMeter, "DecawattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DecawattPerLiter, "DecawattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DeciwattPerCubicFoot, "DeciwattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DeciwattPerCubicInch, "DeciwattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DeciwattPerCubicMeter, "DeciwattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.DeciwattPerLiter, "DeciwattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.GigawattPerCubicFoot, "GigawattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.GigawattPerCubicInch, "GigawattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.GigawattPerCubicMeter, "GigawattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.GigawattPerLiter, "GigawattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.KilowattPerCubicFoot, "KilowattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.KilowattPerCubicInch, "KilowattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.KilowattPerCubicMeter, "KilowattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.KilowattPerLiter, "KilowattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MegawattPerCubicFoot, "MegawattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MegawattPerCubicInch, "MegawattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MegawattPerCubicMeter, "MegawattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MegawattPerLiter, "MegawattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MicrowattPerCubicFoot, "MicrowattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MicrowattPerCubicInch, "MicrowattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MicrowattPerCubicMeter, "MicrowattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MicrowattPerLiter, "MicrowattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MilliwattPerCubicFoot, "MilliwattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MilliwattPerCubicInch, "MilliwattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MilliwattPerCubicMeter, "MilliwattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.MilliwattPerLiter, "MilliwattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.NanowattPerCubicFoot, "NanowattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.NanowattPerCubicInch, "NanowattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.NanowattPerCubicMeter, "NanowattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.NanowattPerLiter, "NanowattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.PicowattPerCubicFoot, "PicowattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.PicowattPerCubicInch, "PicowattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.PicowattPerCubicMeter, "PicowattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.PicowattPerLiter, "PicowattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.TerawattPerCubicFoot, "TerawattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.TerawattPerCubicInch, "TerawattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.TerawattPerCubicMeter, "TerawattsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.TerawattPerLiter, "TerawattsPerLiter", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.WattPerCubicFoot, "WattsPerCubicFoot", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.WattPerCubicInch, "WattsPerCubicInch", BaseUnits.Undefined), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.WattPerCubicMeter, "WattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), + new UnitInfo<PowerDensityUnit>(PowerDensityUnit.WattPerLiter, "WattsPerLiter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public PowerDensity(double value, PowerDensityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="PowerDensity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PowerDensityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. + /// </summary> + public static PowerDensityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the PowerDensity quantity. + /// </summary> + public static PowerDensityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. + /// </summary> + public static PowerDensity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static PowerDensity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PowerDensityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => PowerDensity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DecawattPerCubicFoot"/> + /// </summary> + public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DecawattPerCubicInch"/> + /// </summary> + public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DecawattPerCubicMeter"/> + /// </summary> + public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DecawattPerLiter"/> + /// </summary> + public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DeciwattPerCubicFoot"/> + /// </summary> + public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DeciwattPerCubicInch"/> + /// </summary> + public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DeciwattPerCubicMeter"/> + /// </summary> + public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.DeciwattPerLiter"/> + /// </summary> + public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.GigawattPerCubicFoot"/> + /// </summary> + public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.GigawattPerCubicInch"/> + /// </summary> + public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.GigawattPerCubicMeter"/> + /// </summary> + public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.GigawattPerLiter"/> + /// </summary> + public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.KilowattPerCubicFoot"/> + /// </summary> + public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.KilowattPerCubicInch"/> + /// </summary> + public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.KilowattPerCubicMeter"/> + /// </summary> + public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.KilowattPerLiter"/> + /// </summary> + public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MegawattPerCubicFoot"/> + /// </summary> + public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MegawattPerCubicInch"/> + /// </summary> + public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MegawattPerCubicMeter"/> + /// </summary> + public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MegawattPerLiter"/> + /// </summary> + public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MicrowattPerCubicFoot"/> + /// </summary> + public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MicrowattPerCubicInch"/> + /// </summary> + public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MicrowattPerCubicMeter"/> + /// </summary> + public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MicrowattPerLiter"/> + /// </summary> + public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MilliwattPerCubicFoot"/> + /// </summary> + public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MilliwattPerCubicInch"/> + /// </summary> + public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MilliwattPerCubicMeter"/> + /// </summary> + public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.MilliwattPerLiter"/> + /// </summary> + public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.NanowattPerCubicFoot"/> + /// </summary> + public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.NanowattPerCubicInch"/> + /// </summary> + public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.NanowattPerCubicMeter"/> + /// </summary> + public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.NanowattPerLiter"/> + /// </summary> + public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.PicowattPerCubicFoot"/> + /// </summary> + public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.PicowattPerCubicInch"/> + /// </summary> + public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.PicowattPerCubicMeter"/> + /// </summary> + public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.PicowattPerLiter"/> + /// </summary> + public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.TerawattPerCubicFoot"/> + /// </summary> + public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.TerawattPerCubicInch"/> + /// </summary> + public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.TerawattPerCubicMeter"/> + /// </summary> + public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.TerawattPerLiter"/> + /// </summary> + public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.WattPerCubicFoot"/> + /// </summary> + public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.WattPerCubicInch"/> + /// </summary> + public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.WattPerCubicMeter"/> + /// </summary> + public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerDensityUnit.WattPerLiter"/> + /// </summary> + public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PowerDensityUnit -> BaseUnit + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DecawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DecawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DecawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DecawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DeciwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DeciwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DeciwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.DeciwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.GigawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.GigawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.GigawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.GigawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.KilowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.KilowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.KilowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.KilowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MegawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MegawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MegawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MegawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MicrowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MicrowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MicrowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MicrowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MilliwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MilliwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MilliwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.MilliwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.NanowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.NanowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.NanowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.NanowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.PicowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.PicowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.PicowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.PicowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.TerawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.TerawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.TerawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.TerawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> PowerDensityUnit + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicMeter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerLiter)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicFoot)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicInch)); + unitConverter.SetConversionFunction<PowerDensity>(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerLiter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DecawattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"daW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DecawattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"daW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DecawattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"daW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DecawattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"daW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DeciwattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"dW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DeciwattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"dW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DeciwattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"dW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.DeciwattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"dW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.GigawattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"GW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.GigawattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"GW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.GigawattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"GW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.GigawattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"GW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.KilowattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"kW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.KilowattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"kW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.KilowattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.KilowattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"kW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MegawattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"MW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MegawattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"MW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MegawattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"MW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MegawattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"MW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MicrowattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"µW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MicrowattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"µW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MicrowattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"µW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MicrowattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"µW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MilliwattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"mW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MilliwattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"mW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MilliwattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"mW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.MilliwattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"mW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.NanowattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"nW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.NanowattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"nW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.NanowattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"nW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.NanowattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"nW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.PicowattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"pW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.PicowattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"pW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.PicowattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"pW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.PicowattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"pW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.TerawattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"TW/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.TerawattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"TW/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.TerawattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"TW/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.TerawattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"TW/l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.WattPerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"W/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.WattPerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"W/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.WattPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"W/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerDensityUnit.WattPerLiter, new CultureInfo("en-US"), false, true, new string[]{"W/l"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PowerDensityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PowerDensityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DecawattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue decawattspercubicfoot) + { + double value = (double) decawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DecawattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDecawattsPerCubicInch(QuantityValue decawattspercubicinch) + { + double value = (double) decawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DecawattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue decawattspercubicmeter) + { + double value = (double) decawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DecawattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDecawattsPerLiter(QuantityValue decawattsperliter) + { + double value = (double) decawattsperliter; + return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DeciwattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue deciwattspercubicfoot) + { + double value = (double) deciwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DeciwattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue deciwattspercubicinch) + { + double value = (double) deciwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DeciwattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue deciwattspercubicmeter) + { + double value = (double) deciwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.DeciwattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromDeciwattsPerLiter(QuantityValue deciwattsperliter) + { + double value = (double) deciwattsperliter; + return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.GigawattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue gigawattspercubicfoot) + { + double value = (double) gigawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.GigawattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromGigawattsPerCubicInch(QuantityValue gigawattspercubicinch) + { + double value = (double) gigawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.GigawattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue gigawattspercubicmeter) + { + double value = (double) gigawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.GigawattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromGigawattsPerLiter(QuantityValue gigawattsperliter) + { + double value = (double) gigawattsperliter; + return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.KilowattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue kilowattspercubicfoot) + { + double value = (double) kilowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.KilowattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromKilowattsPerCubicInch(QuantityValue kilowattspercubicinch) + { + double value = (double) kilowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.KilowattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue kilowattspercubicmeter) + { + double value = (double) kilowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.KilowattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromKilowattsPerLiter(QuantityValue kilowattsperliter) + { + double value = (double) kilowattsperliter; + return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MegawattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue megawattspercubicfoot) + { + double value = (double) megawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MegawattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMegawattsPerCubicInch(QuantityValue megawattspercubicinch) + { + double value = (double) megawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MegawattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue megawattspercubicmeter) + { + double value = (double) megawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MegawattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMegawattsPerLiter(QuantityValue megawattsperliter) + { + double value = (double) megawattsperliter; + return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MicrowattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue microwattspercubicfoot) + { + double value = (double) microwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MicrowattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue microwattspercubicinch) + { + double value = (double) microwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MicrowattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue microwattspercubicmeter) + { + double value = (double) microwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MicrowattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMicrowattsPerLiter(QuantityValue microwattsperliter) + { + double value = (double) microwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MilliwattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue milliwattspercubicfoot) + { + double value = (double) milliwattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MilliwattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue milliwattspercubicinch) + { + double value = (double) milliwattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MilliwattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue milliwattspercubicmeter) + { + double value = (double) milliwattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.MilliwattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromMilliwattsPerLiter(QuantityValue milliwattsperliter) + { + double value = (double) milliwattsperliter; + return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.NanowattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue nanowattspercubicfoot) + { + double value = (double) nanowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.NanowattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromNanowattsPerCubicInch(QuantityValue nanowattspercubicinch) + { + double value = (double) nanowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.NanowattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue nanowattspercubicmeter) + { + double value = (double) nanowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.NanowattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromNanowattsPerLiter(QuantityValue nanowattsperliter) + { + double value = (double) nanowattsperliter; + return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.PicowattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue picowattspercubicfoot) + { + double value = (double) picowattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.PicowattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromPicowattsPerCubicInch(QuantityValue picowattspercubicinch) + { + double value = (double) picowattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.PicowattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue picowattspercubicmeter) + { + double value = (double) picowattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.PicowattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromPicowattsPerLiter(QuantityValue picowattsperliter) + { + double value = (double) picowattsperliter; + return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.TerawattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue terawattspercubicfoot) + { + double value = (double) terawattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.TerawattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromTerawattsPerCubicInch(QuantityValue terawattspercubicinch) + { + double value = (double) terawattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.TerawattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue terawattspercubicmeter) + { + double value = (double) terawattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.TerawattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromTerawattsPerLiter(QuantityValue terawattsperliter) + { + double value = (double) terawattsperliter; + return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.WattPerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromWattsPerCubicFoot(QuantityValue wattspercubicfoot) + { + double value = (double) wattspercubicfoot; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.WattPerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromWattsPerCubicInch(QuantityValue wattspercubicinch) + { + double value = (double) wattspercubicinch; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.WattPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromWattsPerCubicMeter(QuantityValue wattspercubicmeter) + { + double value = (double) wattspercubicmeter; + return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="PowerDensity"/> from <see cref="PowerDensityUnit.WattPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerDensity FromWattsPerLiter(QuantityValue wattsperliter) + { + double value = (double) wattsperliter; + return new PowerDensity(value, PowerDensityUnit.WattPerLiter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PowerDensityUnit" /> to <see cref="PowerDensity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>PowerDensity unit value.</returns> + public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) + { + return new PowerDensity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static PowerDensity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static PowerDensity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<PowerDensity, PowerDensityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out PowerDensity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out PowerDensity result) + { + return QuantityParser.Default.TryParse<PowerDensity, PowerDensityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PowerDensityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PowerDensityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PowerDensityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PowerDensityUnit)"/> + public static bool TryParseUnit(string str, out PowerDensityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PowerDensityUnit unit) + { + return UnitParser.Default.TryParse<PowerDensityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static PowerDensity operator -(PowerDensity right) + { + return new PowerDensity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="PowerDensity"/> from adding two <see cref="PowerDensity"/>.</summary> + public static PowerDensity operator +(PowerDensity left, PowerDensity right) + { + return new PowerDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="PowerDensity"/> from subtracting two <see cref="PowerDensity"/>.</summary> + public static PowerDensity operator -(PowerDensity left, PowerDensity right) + { + return new PowerDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="PowerDensity"/> from multiplying value and <see cref="PowerDensity"/>.</summary> + public static PowerDensity operator *(double left, PowerDensity right) + { + return new PowerDensity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="PowerDensity"/> from multiplying value and <see cref="PowerDensity"/>.</summary> + public static PowerDensity operator *(PowerDensity left, double right) + { + return new PowerDensity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="PowerDensity"/> from dividing <see cref="PowerDensity"/> by value.</summary> + public static PowerDensity operator /(PowerDensity left, double right) + { + return new PowerDensity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="PowerDensity"/> by <see cref="PowerDensity"/>.</summary> + public static double operator /(PowerDensity left, PowerDensity right) + { + return left.WattsPerCubicMeter / right.WattsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(PowerDensity left, PowerDensity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(PowerDensity left, PowerDensity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(PowerDensity left, PowerDensity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(PowerDensity left, PowerDensity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="PowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(PowerDensity left, PowerDensity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="PowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(PowerDensity left, PowerDensity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is PowerDensity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PowerDensity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerDensity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(PowerDensity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="PowerDensity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is PowerDensity otherQuantity)) throw new ArgumentException("Expected type PowerDensity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="PowerDensity"/> with another <see cref="PowerDensity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(PowerDensity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another PowerDensity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current PowerDensity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PowerDensityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PowerDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this PowerDensity to another PowerDensity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A PowerDensity with the specified unit.</returns> + public PowerDensity ToUnit(PowerDensityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="PowerDensity"/> to another <see cref="PowerDensity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A PowerDensity with the specified unit.</returns> + public PowerDensity ToUnit(PowerDensityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(PowerDensity), Unit, typeof(PowerDensity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (PowerDensity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="PowerDensity"/> to another <see cref="PowerDensity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="PowerDensity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PowerDensityUnit unit, [NotNullWhen(true)] out PowerDensity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + PowerDensity? convertedOrNull = (Unit, unit) switch + { + // PowerDensityUnit -> BaseUnit + (PowerDensityUnit.DecawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DecawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DecawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DecawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DeciwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DeciwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DeciwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.DeciwattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.GigawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.GigawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.GigawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.GigawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.KilowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.KilowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.KilowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.KilowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MegawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MegawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MegawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MegawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MicrowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MicrowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MicrowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MicrowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MilliwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MilliwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MilliwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.MilliwattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.NanowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.NanowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.NanowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.NanowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.PicowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.PicowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.PicowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.PicowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.TerawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 3.531466672148859e1) * 1e12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.TerawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 6.102374409473228e4) * 1e12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.TerawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.TerawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e12d, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.WattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity(_value * 3.531466672148859e1, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.WattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity(_value * 6.102374409473228e4, PowerDensityUnit.WattPerCubicMeter), + (PowerDensityUnit.WattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity(_value * 1.0e3, PowerDensityUnit.WattPerCubicMeter), + + // BaseUnit -> PowerDensityUnit + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e1d, PowerDensityUnit.DecawattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e1d, PowerDensityUnit.DecawattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicMeter) => new PowerDensity((_value) / 1e1d, PowerDensityUnit.DecawattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e1d, PowerDensityUnit.DecawattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e-1d, PowerDensityUnit.DeciwattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e-1d, PowerDensityUnit.DeciwattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicMeter) => new PowerDensity((_value) / 1e-1d, PowerDensityUnit.DeciwattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-1d, PowerDensityUnit.DeciwattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e9d, PowerDensityUnit.GigawattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e9d, PowerDensityUnit.GigawattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicMeter) => new PowerDensity((_value) / 1e9d, PowerDensityUnit.GigawattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e9d, PowerDensityUnit.GigawattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e3d, PowerDensityUnit.KilowattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e3d, PowerDensityUnit.KilowattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicMeter) => new PowerDensity((_value) / 1e3d, PowerDensityUnit.KilowattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e3d, PowerDensityUnit.KilowattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e6d, PowerDensityUnit.MegawattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e6d, PowerDensityUnit.MegawattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicMeter) => new PowerDensity((_value) / 1e6d, PowerDensityUnit.MegawattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e6d, PowerDensityUnit.MegawattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e-6d, PowerDensityUnit.MicrowattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e-6d, PowerDensityUnit.MicrowattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicMeter) => new PowerDensity((_value) / 1e-6d, PowerDensityUnit.MicrowattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-6d, PowerDensityUnit.MicrowattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e-3d, PowerDensityUnit.MilliwattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e-3d, PowerDensityUnit.MilliwattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicMeter) => new PowerDensity((_value) / 1e-3d, PowerDensityUnit.MilliwattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-3d, PowerDensityUnit.MilliwattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e-9d, PowerDensityUnit.NanowattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e-9d, PowerDensityUnit.NanowattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicMeter) => new PowerDensity((_value) / 1e-9d, PowerDensityUnit.NanowattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-9d, PowerDensityUnit.NanowattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e-12d, PowerDensityUnit.PicowattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e-12d, PowerDensityUnit.PicowattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicMeter) => new PowerDensity((_value) / 1e-12d, PowerDensityUnit.PicowattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-12d, PowerDensityUnit.PicowattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicFoot) => new PowerDensity((_value / 3.531466672148859e1) / 1e12d, PowerDensityUnit.TerawattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicInch) => new PowerDensity((_value / 6.102374409473228e4) / 1e12d, PowerDensityUnit.TerawattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicMeter) => new PowerDensity((_value) / 1e12d, PowerDensityUnit.TerawattPerCubicMeter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e12d, PowerDensityUnit.TerawattPerLiter), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicFoot) => new PowerDensity(_value / 3.531466672148859e1, PowerDensityUnit.WattPerCubicFoot), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicInch) => new PowerDensity(_value / 6.102374409473228e4, PowerDensityUnit.WattPerCubicInch), + (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerLiter) => new PowerDensity(_value / 1.0e3, PowerDensityUnit.WattPerLiter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PowerDensityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PowerDensityUnit> IQuantity<PowerDensityUnit>.ToUnit(PowerDensityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PowerDensityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PowerDensity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PowerDensity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PowerDensity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(PowerDensity)) + return this; + else if (conversionType == typeof(PowerDensityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return PowerDensity.Info; + else if (conversionType == typeof(BaseDimensions)) + return PowerDensity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(PowerDensity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensityUnit.g.cs new file mode 100644 index 0000000000..74a52d1da5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PowerDensity/PowerDensityUnit.g.cs @@ -0,0 +1,75 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PowerDensityUnit + { + DecawattPerCubicFoot = 1, + DecawattPerCubicInch = 2, + DecawattPerCubicMeter = 3, + DecawattPerLiter = 4, + DeciwattPerCubicFoot = 5, + DeciwattPerCubicInch = 6, + DeciwattPerCubicMeter = 7, + DeciwattPerLiter = 8, + GigawattPerCubicFoot = 9, + GigawattPerCubicInch = 10, + GigawattPerCubicMeter = 11, + GigawattPerLiter = 12, + KilowattPerCubicFoot = 13, + KilowattPerCubicInch = 14, + KilowattPerCubicMeter = 15, + KilowattPerLiter = 16, + MegawattPerCubicFoot = 17, + MegawattPerCubicInch = 18, + MegawattPerCubicMeter = 19, + MegawattPerLiter = 20, + MicrowattPerCubicFoot = 21, + MicrowattPerCubicInch = 22, + MicrowattPerCubicMeter = 23, + MicrowattPerLiter = 24, + MilliwattPerCubicFoot = 25, + MilliwattPerCubicInch = 26, + MilliwattPerCubicMeter = 27, + MilliwattPerLiter = 28, + NanowattPerCubicFoot = 29, + NanowattPerCubicInch = 30, + NanowattPerCubicMeter = 31, + NanowattPerLiter = 32, + PicowattPerCubicFoot = 33, + PicowattPerCubicInch = 34, + PicowattPerCubicMeter = 35, + PicowattPerLiter = 36, + TerawattPerCubicFoot = 37, + TerawattPerCubicInch = 38, + TerawattPerCubicMeter = 39, + TerawattPerLiter = 40, + WattPerCubicFoot = 41, + WattPerCubicInch = 42, + WattPerCubicMeter = 43, + WattPerLiter = 44, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatio.csproj b/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatio.csproj new file mode 100644 index 0000000000..869693bc30 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatio.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET PowerRatio</Title> + <Description>Adds PowerRatio units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>powerratio unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{94317d9a-d614-b098-6175-76ee84262c05}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.PowerRatio</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatio.g.cs b/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatio.g.cs new file mode 100644 index 0000000000..7d06064552 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatio.g.cs @@ -0,0 +1,867 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The strength of a signal expressed in decibels (dB) relative to one watt. + /// </summary> + [DataContract] + public readonly partial struct PowerRatio : IArithmeticQuantity<PowerRatio, PowerRatioUnit, double>, IEquatable<PowerRatio>, IComparable, IComparable<PowerRatio>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PowerRatioUnit? _unit; + + static PowerRatio() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = PowerRatioUnit.DecibelWatt; + Units = Enum.GetValues(typeof(PowerRatioUnit)).Cast<PowerRatioUnit>().ToArray(); + Zero = new PowerRatio(0, BaseUnit); + Info = new QuantityInfo<PowerRatioUnit>("PowerRatio", + new UnitInfo<PowerRatioUnit>[] + { + new UnitInfo<PowerRatioUnit>(PowerRatioUnit.DecibelMilliwatt, "DecibelMilliwatts", BaseUnits.Undefined), + new UnitInfo<PowerRatioUnit>(PowerRatioUnit.DecibelWatt, "DecibelWatts", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public PowerRatio(double value, PowerRatioUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="PowerRatio" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PowerRatioUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. + /// </summary> + public static PowerRatioUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the PowerRatio quantity. + /// </summary> + public static PowerRatioUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. + /// </summary> + public static PowerRatio Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static PowerRatio AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PowerRatioUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => PowerRatio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerRatioUnit.DecibelMilliwatt"/> + /// </summary> + public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PowerRatioUnit.DecibelWatt"/> + /// </summary> + public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PowerRatioUnit -> BaseUnit + unitConverter.SetConversionFunction<PowerRatio>(PowerRatioUnit.DecibelMilliwatt, PowerRatioUnit.DecibelWatt, quantity => quantity.ToUnit(PowerRatioUnit.DecibelWatt)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<PowerRatio>(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelWatt, quantity => quantity); + + // Register in unit converter: BaseUnit -> PowerRatioUnit + unitConverter.SetConversionFunction<PowerRatio>(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelMilliwatt, quantity => quantity.ToUnit(PowerRatioUnit.DecibelMilliwatt)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PowerRatioUnit.DecibelMilliwatt, new CultureInfo("en-US"), false, true, new string[]{"dBmW", "dBm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PowerRatioUnit.DecibelWatt, new CultureInfo("en-US"), false, true, new string[]{"dBW"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PowerRatioUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PowerRatioUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="PowerRatio"/> from <see cref="PowerRatioUnit.DecibelMilliwatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) + { + double value = (double) decibelmilliwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); + } + + /// <summary> + /// Creates a <see cref="PowerRatio"/> from <see cref="PowerRatioUnit.DecibelWatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) + { + double value = (double) decibelwatts; + return new PowerRatio(value, PowerRatioUnit.DecibelWatt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PowerRatioUnit" /> to <see cref="PowerRatio" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>PowerRatio unit value.</returns> + public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) + { + return new PowerRatio((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static PowerRatio Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static PowerRatio Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<PowerRatio, PowerRatioUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out PowerRatio result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out PowerRatio result) + { + return QuantityParser.Default.TryParse<PowerRatio, PowerRatioUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PowerRatioUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PowerRatioUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PowerRatioUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PowerRatioUnit)"/> + public static bool TryParseUnit(string str, out PowerRatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PowerRatioUnit unit) + { + return UnitParser.Default.TryParse<PowerRatioUnit>(str, provider, out unit); + } + + #endregion + + #region Logarithmic Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static PowerRatio operator -(PowerRatio right) + { + return new PowerRatio(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="PowerRatio"/> from logarithmic addition of two <see cref="PowerRatio"/>.</summary> + 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.ToUnit(left.Unit).Value / 10)), left.Unit); + } + + /// <summary>Get <see cref="PowerRatio"/> from logarithmic subtraction of two <see cref="PowerRatio"/>.</summary> + 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.ToUnit(left.Unit).Value / 10)), left.Unit); + } + + /// <summary>Get <see cref="PowerRatio"/> from logarithmic multiplication of value and <see cref="PowerRatio"/>.</summary> + public static PowerRatio operator *(double left, PowerRatio right) + { + // Logarithmic multiplication = addition + return new PowerRatio(left + right.Value, right.Unit); + } + + /// <summary>Get <see cref="PowerRatio"/> from logarithmic multiplication of value and <see cref="PowerRatio"/>.</summary> + public static PowerRatio operator *(PowerRatio left, double right) + { + // Logarithmic multiplication = addition + return new PowerRatio(left.Value + (double)right, left.Unit); + } + + /// <summary>Get <see cref="PowerRatio"/> from logarithmic division of <see cref="PowerRatio"/> by value.</summary> + public static PowerRatio operator /(PowerRatio left, double right) + { + // Logarithmic division = subtraction + return new PowerRatio(left.Value - (double)right, left.Unit); + } + + /// <summary>Get ratio value from logarithmic division of <see cref="PowerRatio"/> by <see cref="PowerRatio"/>.</summary> + public static double operator /(PowerRatio left, PowerRatio right) + { + // Logarithmic division = subtraction + return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(PowerRatio left, PowerRatio right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(PowerRatio left, PowerRatio right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(PowerRatio left, PowerRatio right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(PowerRatio left, PowerRatio right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="PowerRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(PowerRatio left, PowerRatio right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="PowerRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(PowerRatio left, PowerRatio right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PowerRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is PowerRatio otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PowerRatio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PowerRatio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(PowerRatio other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="PowerRatio"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is PowerRatio otherQuantity)) throw new ArgumentException("Expected type PowerRatio.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="PowerRatio"/> with another <see cref="PowerRatio"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(PowerRatio other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another PowerRatio within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current PowerRatio.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PowerRatioUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PowerRatioUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this PowerRatio to another PowerRatio with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A PowerRatio with the specified unit.</returns> + public PowerRatio ToUnit(PowerRatioUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="PowerRatio"/> to another <see cref="PowerRatio"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A PowerRatio with the specified unit.</returns> + public PowerRatio ToUnit(PowerRatioUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(PowerRatio), Unit, typeof(PowerRatio), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (PowerRatio)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="PowerRatio"/> to another <see cref="PowerRatio"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="PowerRatio"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PowerRatioUnit unit, [NotNullWhen(true)] out PowerRatio? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + PowerRatio? convertedOrNull = (Unit, unit) switch + { + // PowerRatioUnit -> BaseUnit + (PowerRatioUnit.DecibelMilliwatt, PowerRatioUnit.DecibelWatt) => new PowerRatio(_value - 30, PowerRatioUnit.DecibelWatt), + + // BaseUnit -> PowerRatioUnit + (PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelMilliwatt) => new PowerRatio(_value + 30, PowerRatioUnit.DecibelMilliwatt), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PowerRatioUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PowerRatioUnit> IQuantity<PowerRatioUnit>.ToUnit(PowerRatioUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PowerRatioUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PowerRatio)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PowerRatio)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PowerRatio)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(PowerRatio)) + return this; + else if (conversionType == typeof(PowerRatioUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return PowerRatio.Info; + else if (conversionType == typeof(BaseDimensions)) + return PowerRatio.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(PowerRatio)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatioUnit.g.cs b/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatioUnit.g.cs new file mode 100644 index 0000000000..f0c4dc508c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PowerRatio/PowerRatioUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PowerRatioUnit + { + DecibelMilliwatt = 1, + DecibelWatt = 2, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Pressure/Pressure.csproj b/UnitsNet.Modular/GeneratedCode/Pressure/Pressure.csproj new file mode 100644 index 0000000000..ef700e1909 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Pressure/Pressure.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Pressure</Title> + <Description>Adds Pressure units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>pressure unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f907841f-b1ee-9b12-580e-cfe2324bed03}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Pressure</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Pressure/Pressure.g.cs b/UnitsNet.Modular/GeneratedCode/Pressure/Pressure.g.cs new file mode 100644 index 0000000000..9c7d919d4a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Pressure/Pressure.g.cs @@ -0,0 +1,1835 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct Pressure : IArithmeticQuantity<Pressure, PressureUnit, double>, IEquatable<Pressure>, IComparable, IComparable<Pressure>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PressureUnit? _unit; + + static Pressure() + { + BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); + BaseUnit = PressureUnit.Pascal; + Units = Enum.GetValues(typeof(PressureUnit)).Cast<PressureUnit>().ToArray(); + Zero = new Pressure(0, BaseUnit); + Info = new QuantityInfo<PressureUnit>("Pressure", + new UnitInfo<PressureUnit>[] + { + new UnitInfo<PressureUnit>(PressureUnit.Atmosphere, "Atmospheres", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Bar, "Bars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Centibar, "Centibars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Decapascal, "Decapascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Decibar, "Decibars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.DynePerSquareCentimeter, "DynesPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.FootOfElevation, "FeetOfElevation", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.FootOfHead, "FeetOfHead", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Gigapascal, "Gigapascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Hectopascal, "Hectopascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.InchOfMercury, "InchesOfMercury", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.InchOfWaterColumn, "InchesOfWaterColumn", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Kilobar, "Kilobars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilogramForcePerSquareCentimeter, "KilogramsForcePerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilogramForcePerSquareMeter, "KilogramsForcePerSquareMeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilogramForcePerSquareMillimeter, "KilogramsForcePerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilonewtonPerSquareCentimeter, "KilonewtonsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilonewtonPerSquareMeter, "KilonewtonsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilonewtonPerSquareMillimeter, "KilonewtonsPerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Kilopascal, "Kilopascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilopoundForcePerSquareFoot, "KilopoundsForcePerSquareFoot", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilopoundForcePerSquareInch, "KilopoundsForcePerSquareInch", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.KilopoundForcePerSquareMil, "KilopoundsForcePerSquareMil", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Megabar, "Megabars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.MeganewtonPerSquareMeter, "MeganewtonsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Megapascal, "Megapascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.MeterOfElevation, "MetersOfElevation", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.MeterOfHead, "MetersOfHead", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Microbar, "Microbars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Micropascal, "Micropascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Millibar, "Millibars", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.MillimeterOfMercury, "MillimetersOfMercury", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.MillimeterOfWaterColumn, "MillimeterOfWaterColumn", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Millipascal, "Millipascals", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.NewtonPerSquareCentimeter, "NewtonsPerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.NewtonPerSquareMeter, "NewtonsPerSquareMeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.NewtonPerSquareMillimeter, "NewtonsPerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Pascal, "Pascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)), + new UnitInfo<PressureUnit>(PressureUnit.PoundForcePerSquareFoot, "PoundsForcePerSquareFoot", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.PoundForcePerSquareInch, "PoundsForcePerSquareInch", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.PoundForcePerSquareMil, "PoundsForcePerSquareMil", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.PoundPerInchSecondSquared, "PoundsPerInchSecondSquared", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.TechnicalAtmosphere, "TechnicalAtmospheres", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.TonneForcePerSquareCentimeter, "TonnesForcePerSquareCentimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.TonneForcePerSquareMeter, "TonnesForcePerSquareMeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.TonneForcePerSquareMillimeter, "TonnesForcePerSquareMillimeter", BaseUnits.Undefined), + new UnitInfo<PressureUnit>(PressureUnit.Torr, "Torrs", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Pressure(double value, PressureUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Pressure" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PressureUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Pressure, which is Pascal. All conversions go via this value. + /// </summary> + public static PressureUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Pressure quantity. + /// </summary> + public static PressureUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. + /// </summary> + public static Pressure Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Pressure AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PressureUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Pressure.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Atmosphere"/> + /// </summary> + public double Atmospheres => As(PressureUnit.Atmosphere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Bar"/> + /// </summary> + public double Bars => As(PressureUnit.Bar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Centibar"/> + /// </summary> + public double Centibars => As(PressureUnit.Centibar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Decapascal"/> + /// </summary> + public double Decapascals => As(PressureUnit.Decapascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Decibar"/> + /// </summary> + public double Decibars => As(PressureUnit.Decibar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.DynePerSquareCentimeter"/> + /// </summary> + public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.FootOfElevation"/> + /// </summary> + public double FeetOfElevation => As(PressureUnit.FootOfElevation); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.FootOfHead"/> + /// </summary> + public double FeetOfHead => As(PressureUnit.FootOfHead); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Gigapascal"/> + /// </summary> + public double Gigapascals => As(PressureUnit.Gigapascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Hectopascal"/> + /// </summary> + public double Hectopascals => As(PressureUnit.Hectopascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.InchOfMercury"/> + /// </summary> + public double InchesOfMercury => As(PressureUnit.InchOfMercury); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.InchOfWaterColumn"/> + /// </summary> + public double InchesOfWaterColumn => As(PressureUnit.InchOfWaterColumn); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Kilobar"/> + /// </summary> + public double Kilobars => As(PressureUnit.Kilobar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilogramForcePerSquareCentimeter"/> + /// </summary> + public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilogramForcePerSquareMeter"/> + /// </summary> + public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilogramForcePerSquareMillimeter"/> + /// </summary> + public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilonewtonPerSquareCentimeter"/> + /// </summary> + public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilonewtonPerSquareMeter"/> + /// </summary> + public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilonewtonPerSquareMillimeter"/> + /// </summary> + public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Kilopascal"/> + /// </summary> + public double Kilopascals => As(PressureUnit.Kilopascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilopoundForcePerSquareFoot"/> + /// </summary> + public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilopoundForcePerSquareInch"/> + /// </summary> + public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.KilopoundForcePerSquareMil"/> + /// </summary> + public double KilopoundsForcePerSquareMil => As(PressureUnit.KilopoundForcePerSquareMil); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Megabar"/> + /// </summary> + public double Megabars => As(PressureUnit.Megabar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.MeganewtonPerSquareMeter"/> + /// </summary> + public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Megapascal"/> + /// </summary> + public double Megapascals => As(PressureUnit.Megapascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.MeterOfElevation"/> + /// </summary> + public double MetersOfElevation => As(PressureUnit.MeterOfElevation); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.MeterOfHead"/> + /// </summary> + public double MetersOfHead => As(PressureUnit.MeterOfHead); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Microbar"/> + /// </summary> + public double Microbars => As(PressureUnit.Microbar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Micropascal"/> + /// </summary> + public double Micropascals => As(PressureUnit.Micropascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Millibar"/> + /// </summary> + public double Millibars => As(PressureUnit.Millibar); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.MillimeterOfMercury"/> + /// </summary> + public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.MillimeterOfWaterColumn"/> + /// </summary> + public double MillimeterOfWaterColumn => As(PressureUnit.MillimeterOfWaterColumn); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Millipascal"/> + /// </summary> + public double Millipascals => As(PressureUnit.Millipascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.NewtonPerSquareCentimeter"/> + /// </summary> + public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.NewtonPerSquareMeter"/> + /// </summary> + public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.NewtonPerSquareMillimeter"/> + /// </summary> + public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Pascal"/> + /// </summary> + public double Pascals => As(PressureUnit.Pascal); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.PoundForcePerSquareFoot"/> + /// </summary> + public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.PoundForcePerSquareInch"/> + /// </summary> + public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.PoundForcePerSquareMil"/> + /// </summary> + public double PoundsForcePerSquareMil => As(PressureUnit.PoundForcePerSquareMil); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.PoundPerInchSecondSquared"/> + /// </summary> + public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.TechnicalAtmosphere"/> + /// </summary> + public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.TonneForcePerSquareCentimeter"/> + /// </summary> + public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.TonneForcePerSquareMeter"/> + /// </summary> + public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.TonneForcePerSquareMillimeter"/> + /// </summary> + public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureUnit.Torr"/> + /// </summary> + public double Torrs => As(PressureUnit.Torr); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PressureUnit -> BaseUnit + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Atmosphere, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Bar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Centibar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Decapascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Decibar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.DynePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.FootOfElevation, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.FootOfHead, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Gigapascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Hectopascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.InchOfMercury, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.InchOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Kilobar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilogramForcePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilogramForcePerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilogramForcePerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilonewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilonewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilonewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Kilopascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilopoundForcePerSquareFoot, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilopoundForcePerSquareInch, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.KilopoundForcePerSquareMil, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Megabar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.MeganewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Megapascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.MeterOfElevation, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.MeterOfHead, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Microbar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Micropascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Millibar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.MillimeterOfMercury, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.MillimeterOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Millipascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.NewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.NewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.NewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.PoundForcePerSquareFoot, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.PoundForcePerSquareInch, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.PoundForcePerSquareMil, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.PoundPerInchSecondSquared, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.TechnicalAtmosphere, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.TonneForcePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.TonneForcePerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.TonneForcePerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Torr, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Pascal, quantity => quantity); + + // Register in unit converter: BaseUnit -> PressureUnit + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Atmosphere, quantity => quantity.ToUnit(PressureUnit.Atmosphere)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Bar, quantity => quantity.ToUnit(PressureUnit.Bar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Centibar, quantity => quantity.ToUnit(PressureUnit.Centibar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Decapascal, quantity => quantity.ToUnit(PressureUnit.Decapascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Decibar, quantity => quantity.ToUnit(PressureUnit.Decibar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.DynePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.DynePerSquareCentimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.FootOfElevation, quantity => quantity.ToUnit(PressureUnit.FootOfElevation)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.FootOfHead, quantity => quantity.ToUnit(PressureUnit.FootOfHead)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Gigapascal, quantity => quantity.ToUnit(PressureUnit.Gigapascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Hectopascal, quantity => quantity.ToUnit(PressureUnit.Hectopascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.InchOfMercury, quantity => quantity.ToUnit(PressureUnit.InchOfMercury)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.InchOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.InchOfWaterColumn)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Kilobar, quantity => quantity.ToUnit(PressureUnit.Kilobar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareCentimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareMeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareMillimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareCentimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareMeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareMillimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Kilopascal, quantity => quantity.ToUnit(PressureUnit.Kilopascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareFoot, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareFoot)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareInch, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareInch)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareMil, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareMil)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Megabar, quantity => quantity.ToUnit(PressureUnit.Megabar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.MeganewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.MeganewtonPerSquareMeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Megapascal, quantity => quantity.ToUnit(PressureUnit.Megapascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.MeterOfElevation, quantity => quantity.ToUnit(PressureUnit.MeterOfElevation)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.MeterOfHead, quantity => quantity.ToUnit(PressureUnit.MeterOfHead)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Microbar, quantity => quantity.ToUnit(PressureUnit.Microbar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Micropascal, quantity => quantity.ToUnit(PressureUnit.Micropascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Millibar, quantity => quantity.ToUnit(PressureUnit.Millibar)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.MillimeterOfMercury, quantity => quantity.ToUnit(PressureUnit.MillimeterOfMercury)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.MillimeterOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.MillimeterOfWaterColumn)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Millipascal, quantity => quantity.ToUnit(PressureUnit.Millipascal)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.NewtonPerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareCentimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareMeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareMillimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareFoot, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareFoot)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareInch, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareInch)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareMil, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareMil)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.PoundPerInchSecondSquared, quantity => quantity.ToUnit(PressureUnit.PoundPerInchSecondSquared)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.TechnicalAtmosphere, quantity => quantity.ToUnit(PressureUnit.TechnicalAtmosphere)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareCentimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareMeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareMillimeter)); + unitConverter.SetConversionFunction<Pressure>(PressureUnit.Pascal, PressureUnit.Torr, quantity => quantity.ToUnit(PressureUnit.Torr)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Atmosphere, new CultureInfo("en-US"), false, true, new string[]{"atm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Atmosphere, new CultureInfo("ru-RU"), false, true, new string[]{"атм"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Bar, new CultureInfo("en-US"), false, true, new string[]{"bar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Bar, new CultureInfo("ru-RU"), false, true, new string[]{"бар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Centibar, new CultureInfo("en-US"), false, true, new string[]{"cbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Centibar, new CultureInfo("ru-RU"), false, true, new string[]{"сбар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Decapascal, new CultureInfo("en-US"), false, true, new string[]{"daPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Decapascal, new CultureInfo("ru-RU"), false, true, new string[]{"даПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Decibar, new CultureInfo("en-US"), false, true, new string[]{"dbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Decibar, new CultureInfo("ru-RU"), false, true, new string[]{"дбар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.DynePerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"dyn/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.FootOfElevation, new CultureInfo("en-US"), false, true, new string[]{"ft of elevation"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.FootOfHead, new CultureInfo("en-US"), false, true, new string[]{"ft of head"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Gigapascal, new CultureInfo("en-US"), false, true, new string[]{"GPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Gigapascal, new CultureInfo("ru-RU"), false, true, new string[]{"ГПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Hectopascal, new CultureInfo("en-US"), false, true, new string[]{"hPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Hectopascal, new CultureInfo("ru-RU"), false, true, new string[]{"гПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.InchOfMercury, new CultureInfo("en-US"), false, true, new string[]{"inHg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.InchOfWaterColumn, new CultureInfo("en-US"), false, true, new string[]{"inH2O", "inch wc", "wc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Kilobar, new CultureInfo("en-US"), false, true, new string[]{"kbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Kilobar, new CultureInfo("ru-RU"), false, true, new string[]{"кбар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilogramForcePerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilogramForcePerSquareCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"кгс/см²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilogramForcePerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilogramForcePerSquareMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кгс/м²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilogramForcePerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilogramForcePerSquareMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"кгс/мм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilonewtonPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kN/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilonewtonPerSquareCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"кН/см²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilonewtonPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"kN/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilonewtonPerSquareMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кН/м²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilonewtonPerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kN/mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilonewtonPerSquareMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"кН/мм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Kilopascal, new CultureInfo("en-US"), false, true, new string[]{"kPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Kilopascal, new CultureInfo("ru-RU"), false, true, new string[]{"кПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilopoundForcePerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilopoundForcePerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"ksi", "kipf/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilopoundForcePerSquareInch, new CultureInfo("ru-RU"), false, true, new string[]{"ksi", "kipf/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.KilopoundForcePerSquareMil, new CultureInfo("en-US"), false, true, new string[]{"kipf/mil²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Megabar, new CultureInfo("en-US"), false, true, new string[]{"Mbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Megabar, new CultureInfo("ru-RU"), false, true, new string[]{"Мбар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MeganewtonPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"MN/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MeganewtonPerSquareMeter, new CultureInfo("ru-RU"), false, true, new string[]{"МН/м²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Megapascal, new CultureInfo("en-US"), false, true, new string[]{"MPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Megapascal, new CultureInfo("ru-RU"), false, true, new string[]{"МПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MeterOfElevation, new CultureInfo("en-US"), false, true, new string[]{"m of elevation"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MeterOfHead, new CultureInfo("en-US"), false, true, new string[]{"m of head"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Microbar, new CultureInfo("en-US"), false, true, new string[]{"µbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Microbar, new CultureInfo("ru-RU"), false, true, new string[]{"мкбар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Micropascal, new CultureInfo("en-US"), false, true, new string[]{"µPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Micropascal, new CultureInfo("ru-RU"), false, true, new string[]{"мкПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Millibar, new CultureInfo("en-US"), false, true, new string[]{"mbar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Millibar, new CultureInfo("ru-RU"), false, true, new string[]{"мбар"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MillimeterOfMercury, new CultureInfo("en-US"), false, true, new string[]{"mmHg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MillimeterOfMercury, new CultureInfo("ru-RU"), false, true, new string[]{"мм рт.ст."}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.MillimeterOfWaterColumn, new CultureInfo("en-US"), false, true, new string[]{"mmH2O", "mm wc"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Millipascal, new CultureInfo("en-US"), false, true, new string[]{"mPa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Millipascal, new CultureInfo("ru-RU"), false, true, new string[]{"мПа"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.NewtonPerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"N/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.NewtonPerSquareCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"Н/см²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.NewtonPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"N/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.NewtonPerSquareMeter, new CultureInfo("ru-RU"), false, true, new string[]{"Н/м²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.NewtonPerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"N/mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.NewtonPerSquareMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"Н/мм²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Pascal, new CultureInfo("en-US"), false, true, new string[]{"Pa"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Pascal, new CultureInfo("ru-RU"), false, true, new string[]{"Па"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.PoundForcePerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"lb/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.PoundForcePerSquareInch, new CultureInfo("en-US"), false, true, new string[]{"psi", "lb/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.PoundForcePerSquareInch, new CultureInfo("ru-RU"), false, true, new string[]{"psi", "lb/in²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.PoundForcePerSquareMil, new CultureInfo("en-US"), false, true, new string[]{"lb/mil²", "lbs/mil²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.PoundPerInchSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"lbm/(in·s²)", "lb/(in·s²)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.TechnicalAtmosphere, new CultureInfo("en-US"), false, true, new string[]{"at"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.TechnicalAtmosphere, new CultureInfo("ru-RU"), false, true, new string[]{"ат"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.TonneForcePerSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"tf/cm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.TonneForcePerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"tf/m²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.TonneForcePerSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"tf/mm²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Torr, new CultureInfo("en-US"), false, true, new string[]{"torr"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureUnit.Torr, new CultureInfo("ru-RU"), false, true, new string[]{"торр"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PressureUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PressureUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Atmosphere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromAtmospheres(QuantityValue atmospheres) + { + double value = (double) atmospheres; + return new Pressure(value, PressureUnit.Atmosphere); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Bar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromBars(QuantityValue bars) + { + double value = (double) bars; + return new Pressure(value, PressureUnit.Bar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Centibar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromCentibars(QuantityValue centibars) + { + double value = (double) centibars; + return new Pressure(value, PressureUnit.Centibar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Decapascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromDecapascals(QuantityValue decapascals) + { + double value = (double) decapascals; + return new Pressure(value, PressureUnit.Decapascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Decibar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromDecibars(QuantityValue decibars) + { + double value = (double) decibars; + return new Pressure(value, PressureUnit.Decibar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.DynePerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromDynesPerSquareCentimeter(QuantityValue dynespersquarecentimeter) + { + double value = (double) dynespersquarecentimeter; + return new Pressure(value, PressureUnit.DynePerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.FootOfElevation"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromFeetOfElevation(QuantityValue feetofelevation) + { + double value = (double) feetofelevation; + return new Pressure(value, PressureUnit.FootOfElevation); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.FootOfHead"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromFeetOfHead(QuantityValue feetofhead) + { + double value = (double) feetofhead; + return new Pressure(value, PressureUnit.FootOfHead); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Gigapascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromGigapascals(QuantityValue gigapascals) + { + double value = (double) gigapascals; + return new Pressure(value, PressureUnit.Gigapascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Hectopascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromHectopascals(QuantityValue hectopascals) + { + double value = (double) hectopascals; + return new Pressure(value, PressureUnit.Hectopascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.InchOfMercury"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) + { + double value = (double) inchesofmercury; + return new Pressure(value, PressureUnit.InchOfMercury); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.InchOfWaterColumn"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromInchesOfWaterColumn(QuantityValue inchesofwatercolumn) + { + double value = (double) inchesofwatercolumn; + return new Pressure(value, PressureUnit.InchOfWaterColumn); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Kilobar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilobars(QuantityValue kilobars) + { + double value = (double) kilobars; + return new Pressure(value, PressureUnit.Kilobar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilogramForcePerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) + { + double value = (double) kilogramsforcepersquarecentimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilogramForcePerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) + { + double value = (double) kilogramsforcepersquaremeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilogramForcePerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) + { + double value = (double) kilogramsforcepersquaremillimeter; + return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilonewtonPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) + { + double value = (double) kilonewtonspersquarecentimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilonewtonPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) + { + double value = (double) kilonewtonspersquaremeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilonewtonPerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) + { + double value = (double) kilonewtonspersquaremillimeter; + return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Kilopascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilopascals(QuantityValue kilopascals) + { + double value = (double) kilopascals; + return new Pressure(value, PressureUnit.Kilopascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilopoundForcePerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) + { + double value = (double) kilopoundsforcepersquarefoot; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilopoundForcePerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) + { + double value = (double) kilopoundsforcepersquareinch; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.KilopoundForcePerSquareMil"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromKilopoundsForcePerSquareMil(QuantityValue kilopoundsforcepersquaremil) + { + double value = (double) kilopoundsforcepersquaremil; + return new Pressure(value, PressureUnit.KilopoundForcePerSquareMil); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Megabar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMegabars(QuantityValue megabars) + { + double value = (double) megabars; + return new Pressure(value, PressureUnit.Megabar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.MeganewtonPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue meganewtonspersquaremeter) + { + double value = (double) meganewtonspersquaremeter; + return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Megapascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMegapascals(QuantityValue megapascals) + { + double value = (double) megapascals; + return new Pressure(value, PressureUnit.Megapascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.MeterOfElevation"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMetersOfElevation(QuantityValue metersofelevation) + { + double value = (double) metersofelevation; + return new Pressure(value, PressureUnit.MeterOfElevation); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.MeterOfHead"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMetersOfHead(QuantityValue metersofhead) + { + double value = (double) metersofhead; + return new Pressure(value, PressureUnit.MeterOfHead); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Microbar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMicrobars(QuantityValue microbars) + { + double value = (double) microbars; + return new Pressure(value, PressureUnit.Microbar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Micropascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMicropascals(QuantityValue micropascals) + { + double value = (double) micropascals; + return new Pressure(value, PressureUnit.Micropascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Millibar"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMillibars(QuantityValue millibars) + { + double value = (double) millibars; + return new Pressure(value, PressureUnit.Millibar); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.MillimeterOfMercury"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) + { + double value = (double) millimetersofmercury; + return new Pressure(value, PressureUnit.MillimeterOfMercury); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.MillimeterOfWaterColumn"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMillimeterOfWaterColumn(QuantityValue millimeterofwatercolumn) + { + double value = (double) millimeterofwatercolumn; + return new Pressure(value, PressureUnit.MillimeterOfWaterColumn); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Millipascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromMillipascals(QuantityValue millipascals) + { + double value = (double) millipascals; + return new Pressure(value, PressureUnit.Millipascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.NewtonPerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) + { + double value = (double) newtonspersquarecentimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.NewtonPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) + { + double value = (double) newtonspersquaremeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.NewtonPerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) + { + double value = (double) newtonspersquaremillimeter; + return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Pascal"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromPascals(QuantityValue pascals) + { + double value = (double) pascals; + return new Pressure(value, PressureUnit.Pascal); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.PoundForcePerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) + { + double value = (double) poundsforcepersquarefoot; + return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.PoundForcePerSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) + { + double value = (double) poundsforcepersquareinch; + return new Pressure(value, PressureUnit.PoundForcePerSquareInch); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.PoundForcePerSquareMil"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromPoundsForcePerSquareMil(QuantityValue poundsforcepersquaremil) + { + double value = (double) poundsforcepersquaremil; + return new Pressure(value, PressureUnit.PoundForcePerSquareMil); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.PoundPerInchSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromPoundsPerInchSecondSquared(QuantityValue poundsperinchsecondsquared) + { + double value = (double) poundsperinchsecondsquared; + return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.TechnicalAtmosphere"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) + { + double value = (double) technicalatmospheres; + return new Pressure(value, PressureUnit.TechnicalAtmosphere); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.TonneForcePerSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) + { + double value = (double) tonnesforcepersquarecentimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.TonneForcePerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) + { + double value = (double) tonnesforcepersquaremeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.TonneForcePerSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) + { + double value = (double) tonnesforcepersquaremillimeter; + return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="Pressure"/> from <see cref="PressureUnit.Torr"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Pressure FromTorrs(QuantityValue torrs) + { + double value = (double) torrs; + return new Pressure(value, PressureUnit.Torr); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PressureUnit" /> to <see cref="Pressure" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Pressure unit value.</returns> + public static Pressure From(QuantityValue value, PressureUnit fromUnit) + { + return new Pressure((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Pressure Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Pressure Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Pressure, PressureUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Pressure result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Pressure result) + { + return QuantityParser.Default.TryParse<Pressure, PressureUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PressureUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PressureUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PressureUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PressureUnit)"/> + public static bool TryParseUnit(string str, out PressureUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PressureUnit unit) + { + return UnitParser.Default.TryParse<PressureUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Pressure operator -(Pressure right) + { + return new Pressure(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Pressure"/> from adding two <see cref="Pressure"/>.</summary> + public static Pressure operator +(Pressure left, Pressure right) + { + return new Pressure(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Pressure"/> from subtracting two <see cref="Pressure"/>.</summary> + public static Pressure operator -(Pressure left, Pressure right) + { + return new Pressure(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Pressure"/> from multiplying value and <see cref="Pressure"/>.</summary> + public static Pressure operator *(double left, Pressure right) + { + return new Pressure(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Pressure"/> from multiplying value and <see cref="Pressure"/>.</summary> + public static Pressure operator *(Pressure left, double right) + { + return new Pressure(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Pressure"/> from dividing <see cref="Pressure"/> by value.</summary> + public static Pressure operator /(Pressure left, double right) + { + return new Pressure(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Pressure"/> by <see cref="Pressure"/>.</summary> + public static double operator /(Pressure left, Pressure right) + { + return left.Pascals / right.Pascals; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Pressure left, Pressure right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Pressure left, Pressure right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Pressure left, Pressure right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Pressure left, Pressure right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Pressure"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Pressure, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Pressure left, Pressure right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Pressure"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Pressure, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Pressure left, Pressure right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Pressure"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Pressure, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Pressure otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Pressure"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Pressure, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Pressure other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Pressure"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Pressure otherQuantity)) throw new ArgumentException("Expected type Pressure.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Pressure"/> with another <see cref="Pressure"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Pressure other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Pressure within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Pressure.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PressureUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PressureUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Pressure to another Pressure with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Pressure with the specified unit.</returns> + public Pressure ToUnit(PressureUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Pressure"/> to another <see cref="Pressure"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Pressure with the specified unit.</returns> + public Pressure ToUnit(PressureUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Pressure), Unit, typeof(Pressure), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Pressure)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Pressure"/> to another <see cref="Pressure"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Pressure"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PressureUnit unit, [NotNullWhen(true)] out Pressure? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Pressure? convertedOrNull = (Unit, unit) switch + { + // PressureUnit -> BaseUnit + (PressureUnit.Atmosphere, PressureUnit.Pascal) => new Pressure(_value * 1.01325 * 1e5, PressureUnit.Pascal), + (PressureUnit.Bar, PressureUnit.Pascal) => new Pressure(_value * 1e5, PressureUnit.Pascal), + (PressureUnit.Centibar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-2d, PressureUnit.Pascal), + (PressureUnit.Decapascal, PressureUnit.Pascal) => new Pressure((_value) * 1e1d, PressureUnit.Pascal), + (PressureUnit.Decibar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-1d, PressureUnit.Pascal), + (PressureUnit.DynePerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 1.0e-1, PressureUnit.Pascal), + (PressureUnit.FootOfElevation, PressureUnit.Pascal) => new Pressure(Math.Pow(1.0 - (_value / 145366.45), 5.2553026003237266401799415610351) * 101325.0, PressureUnit.Pascal), + (PressureUnit.FootOfHead, PressureUnit.Pascal) => new Pressure(_value * 2989.0669, PressureUnit.Pascal), + (PressureUnit.Gigapascal, PressureUnit.Pascal) => new Pressure((_value) * 1e9d, PressureUnit.Pascal), + (PressureUnit.Hectopascal, PressureUnit.Pascal) => new Pressure((_value) * 1e2d, PressureUnit.Pascal), + (PressureUnit.InchOfMercury, PressureUnit.Pascal) => new Pressure(_value / 2.95299830714159e-4, PressureUnit.Pascal), + (PressureUnit.InchOfWaterColumn, PressureUnit.Pascal) => new Pressure(_value * 249.08890833333, PressureUnit.Pascal), + (PressureUnit.Kilobar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e3d, PressureUnit.Pascal), + (PressureUnit.KilogramForcePerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e4, PressureUnit.Pascal), + (PressureUnit.KilogramForcePerSquareMeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665019960652, PressureUnit.Pascal), + (PressureUnit.KilogramForcePerSquareMillimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e6, PressureUnit.Pascal), + (PressureUnit.KilonewtonPerSquareCentimeter, PressureUnit.Pascal) => new Pressure((_value * 1e4) * 1e3d, PressureUnit.Pascal), + (PressureUnit.KilonewtonPerSquareMeter, PressureUnit.Pascal) => new Pressure((_value) * 1e3d, PressureUnit.Pascal), + (PressureUnit.KilonewtonPerSquareMillimeter, PressureUnit.Pascal) => new Pressure((_value * 1e6) * 1e3d, PressureUnit.Pascal), + (PressureUnit.Kilopascal, PressureUnit.Pascal) => new Pressure((_value) * 1e3d, PressureUnit.Pascal), + (PressureUnit.KilopoundForcePerSquareFoot, PressureUnit.Pascal) => new Pressure((_value * 4.788025898033584e1) * 1e3d, PressureUnit.Pascal), + (PressureUnit.KilopoundForcePerSquareInch, PressureUnit.Pascal) => new Pressure((_value * 6.894757293168361e3) * 1e3d, PressureUnit.Pascal), + (PressureUnit.KilopoundForcePerSquareMil, PressureUnit.Pascal) => new Pressure((_value * 6.894757293168361e9) * 1e3d, PressureUnit.Pascal), + (PressureUnit.Megabar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e6d, PressureUnit.Pascal), + (PressureUnit.MeganewtonPerSquareMeter, PressureUnit.Pascal) => new Pressure((_value) * 1e6d, PressureUnit.Pascal), + (PressureUnit.Megapascal, PressureUnit.Pascal) => new Pressure((_value) * 1e6d, PressureUnit.Pascal), + (PressureUnit.MeterOfElevation, PressureUnit.Pascal) => new Pressure(Math.Pow(1.0 - (_value / 44307.69396), 5.2553026003237266401799415610351) * 101325.0, PressureUnit.Pascal), + (PressureUnit.MeterOfHead, PressureUnit.Pascal) => new Pressure(_value * 9804.139432, PressureUnit.Pascal), + (PressureUnit.Microbar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-6d, PressureUnit.Pascal), + (PressureUnit.Micropascal, PressureUnit.Pascal) => new Pressure((_value) * 1e-6d, PressureUnit.Pascal), + (PressureUnit.Millibar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-3d, PressureUnit.Pascal), + (PressureUnit.MillimeterOfMercury, PressureUnit.Pascal) => new Pressure(_value / 7.50061561302643e-3, PressureUnit.Pascal), + (PressureUnit.MillimeterOfWaterColumn, PressureUnit.Pascal) => new Pressure(_value * 9.806650000000272e0, PressureUnit.Pascal), + (PressureUnit.Millipascal, PressureUnit.Pascal) => new Pressure((_value) * 1e-3d, PressureUnit.Pascal), + (PressureUnit.NewtonPerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 1e4, PressureUnit.Pascal), + (PressureUnit.NewtonPerSquareMeter, PressureUnit.Pascal) => new Pressure(_value, PressureUnit.Pascal), + (PressureUnit.NewtonPerSquareMillimeter, PressureUnit.Pascal) => new Pressure(_value * 1e6, PressureUnit.Pascal), + (PressureUnit.PoundForcePerSquareFoot, PressureUnit.Pascal) => new Pressure(_value * 4.788025898033584e1, PressureUnit.Pascal), + (PressureUnit.PoundForcePerSquareInch, PressureUnit.Pascal) => new Pressure(_value * 6.894757293168361e3, PressureUnit.Pascal), + (PressureUnit.PoundForcePerSquareMil, PressureUnit.Pascal) => new Pressure(_value * 6.894757293168361e9, PressureUnit.Pascal), + (PressureUnit.PoundPerInchSecondSquared, PressureUnit.Pascal) => new Pressure(_value * 1.785796732283465e1, PressureUnit.Pascal), + (PressureUnit.TechnicalAtmosphere, PressureUnit.Pascal) => new Pressure(_value * 9.80680592331 * 1e4, PressureUnit.Pascal), + (PressureUnit.TonneForcePerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e7, PressureUnit.Pascal), + (PressureUnit.TonneForcePerSquareMeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e3, PressureUnit.Pascal), + (PressureUnit.TonneForcePerSquareMillimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e9, PressureUnit.Pascal), + (PressureUnit.Torr, PressureUnit.Pascal) => new Pressure(_value * 1.3332266752 * 1e2, PressureUnit.Pascal), + + // BaseUnit -> PressureUnit + (PressureUnit.Pascal, PressureUnit.Atmosphere) => new Pressure(_value / (1.01325 * 1e5), PressureUnit.Atmosphere), + (PressureUnit.Pascal, PressureUnit.Bar) => new Pressure(_value / 1e5, PressureUnit.Bar), + (PressureUnit.Pascal, PressureUnit.Centibar) => new Pressure((_value / 1e5) / 1e-2d, PressureUnit.Centibar), + (PressureUnit.Pascal, PressureUnit.Decapascal) => new Pressure((_value) / 1e1d, PressureUnit.Decapascal), + (PressureUnit.Pascal, PressureUnit.Decibar) => new Pressure((_value / 1e5) / 1e-1d, PressureUnit.Decibar), + (PressureUnit.Pascal, PressureUnit.DynePerSquareCentimeter) => new Pressure(_value / 1.0e-1, PressureUnit.DynePerSquareCentimeter), + (PressureUnit.Pascal, PressureUnit.FootOfElevation) => new Pressure((1.0 - Math.Pow(_value / 101325.0, 0.190284)) * 145366.45, PressureUnit.FootOfElevation), + (PressureUnit.Pascal, PressureUnit.FootOfHead) => new Pressure(_value * 0.000334552565551, PressureUnit.FootOfHead), + (PressureUnit.Pascal, PressureUnit.Gigapascal) => new Pressure((_value) / 1e9d, PressureUnit.Gigapascal), + (PressureUnit.Pascal, PressureUnit.Hectopascal) => new Pressure((_value) / 1e2d, PressureUnit.Hectopascal), + (PressureUnit.Pascal, PressureUnit.InchOfMercury) => new Pressure(_value * 2.95299830714159e-4, PressureUnit.InchOfMercury), + (PressureUnit.Pascal, PressureUnit.InchOfWaterColumn) => new Pressure(_value / 249.08890833333, PressureUnit.InchOfWaterColumn), + (PressureUnit.Pascal, PressureUnit.Kilobar) => new Pressure((_value / 1e5) / 1e3d, PressureUnit.Kilobar), + (PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareCentimeter) => new Pressure(_value / 9.80665e4, PressureUnit.KilogramForcePerSquareCentimeter), + (PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMeter) => new Pressure(_value * 0.101971619222242, PressureUnit.KilogramForcePerSquareMeter), + (PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMillimeter) => new Pressure(_value / 9.80665e6, PressureUnit.KilogramForcePerSquareMillimeter), + (PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareCentimeter) => new Pressure((_value / 1e4) / 1e3d, PressureUnit.KilonewtonPerSquareCentimeter), + (PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMeter) => new Pressure((_value) / 1e3d, PressureUnit.KilonewtonPerSquareMeter), + (PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMillimeter) => new Pressure((_value / 1e6) / 1e3d, PressureUnit.KilonewtonPerSquareMillimeter), + (PressureUnit.Pascal, PressureUnit.Kilopascal) => new Pressure((_value) / 1e3d, PressureUnit.Kilopascal), + (PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareFoot) => new Pressure((_value / 4.788025898033584e1) / 1e3d, PressureUnit.KilopoundForcePerSquareFoot), + (PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareInch) => new Pressure((_value / 6.894757293168361e3) / 1e3d, PressureUnit.KilopoundForcePerSquareInch), + (PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareMil) => new Pressure((_value / 6.894757293168361e9) / 1e3d, PressureUnit.KilopoundForcePerSquareMil), + (PressureUnit.Pascal, PressureUnit.Megabar) => new Pressure((_value / 1e5) / 1e6d, PressureUnit.Megabar), + (PressureUnit.Pascal, PressureUnit.MeganewtonPerSquareMeter) => new Pressure((_value) / 1e6d, PressureUnit.MeganewtonPerSquareMeter), + (PressureUnit.Pascal, PressureUnit.Megapascal) => new Pressure((_value) / 1e6d, PressureUnit.Megapascal), + (PressureUnit.Pascal, PressureUnit.MeterOfElevation) => new Pressure((1.0 - Math.Pow(_value / 101325.0, 0.190284)) * 44307.69396, PressureUnit.MeterOfElevation), + (PressureUnit.Pascal, PressureUnit.MeterOfHead) => new Pressure(_value * 0.0001019977334, PressureUnit.MeterOfHead), + (PressureUnit.Pascal, PressureUnit.Microbar) => new Pressure((_value / 1e5) / 1e-6d, PressureUnit.Microbar), + (PressureUnit.Pascal, PressureUnit.Micropascal) => new Pressure((_value) / 1e-6d, PressureUnit.Micropascal), + (PressureUnit.Pascal, PressureUnit.Millibar) => new Pressure((_value / 1e5) / 1e-3d, PressureUnit.Millibar), + (PressureUnit.Pascal, PressureUnit.MillimeterOfMercury) => new Pressure(_value * 7.50061561302643e-3, PressureUnit.MillimeterOfMercury), + (PressureUnit.Pascal, PressureUnit.MillimeterOfWaterColumn) => new Pressure(_value / 9.806650000000272e0, PressureUnit.MillimeterOfWaterColumn), + (PressureUnit.Pascal, PressureUnit.Millipascal) => new Pressure((_value) / 1e-3d, PressureUnit.Millipascal), + (PressureUnit.Pascal, PressureUnit.NewtonPerSquareCentimeter) => new Pressure(_value / 1e4, PressureUnit.NewtonPerSquareCentimeter), + (PressureUnit.Pascal, PressureUnit.NewtonPerSquareMeter) => new Pressure(_value, PressureUnit.NewtonPerSquareMeter), + (PressureUnit.Pascal, PressureUnit.NewtonPerSquareMillimeter) => new Pressure(_value / 1e6, PressureUnit.NewtonPerSquareMillimeter), + (PressureUnit.Pascal, PressureUnit.PoundForcePerSquareFoot) => new Pressure(_value / 4.788025898033584e1, PressureUnit.PoundForcePerSquareFoot), + (PressureUnit.Pascal, PressureUnit.PoundForcePerSquareInch) => new Pressure(_value / 6.894757293168361e3, PressureUnit.PoundForcePerSquareInch), + (PressureUnit.Pascal, PressureUnit.PoundForcePerSquareMil) => new Pressure(_value / 6.894757293168361e9, PressureUnit.PoundForcePerSquareMil), + (PressureUnit.Pascal, PressureUnit.PoundPerInchSecondSquared) => new Pressure(_value / 1.785796732283465e1, PressureUnit.PoundPerInchSecondSquared), + (PressureUnit.Pascal, PressureUnit.TechnicalAtmosphere) => new Pressure(_value / (9.80680592331 * 1e4), PressureUnit.TechnicalAtmosphere), + (PressureUnit.Pascal, PressureUnit.TonneForcePerSquareCentimeter) => new Pressure(_value / 9.80665e7, PressureUnit.TonneForcePerSquareCentimeter), + (PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMeter) => new Pressure(_value / 9.80665e3, PressureUnit.TonneForcePerSquareMeter), + (PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMillimeter) => new Pressure(_value / 9.80665e9, PressureUnit.TonneForcePerSquareMillimeter), + (PressureUnit.Pascal, PressureUnit.Torr) => new Pressure(_value / (1.3332266752 * 1e2), PressureUnit.Torr), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PressureUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PressureUnit> IQuantity<PressureUnit>.ToUnit(PressureUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PressureUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Pressure)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Pressure)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Pressure)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Pressure)) + return this; + else if (conversionType == typeof(PressureUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Pressure.Info; + else if (conversionType == typeof(BaseDimensions)) + return Pressure.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Pressure)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Pressure/PressureUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Pressure/PressureUnit.g.cs new file mode 100644 index 0000000000..5d832b88b1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Pressure/PressureUnit.g.cs @@ -0,0 +1,78 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PressureUnit + { + Atmosphere = 1, + Bar = 2, + Centibar = 3, + Decapascal = 4, + Decibar = 5, + DynePerSquareCentimeter = 6, + FootOfElevation = 7, + FootOfHead = 8, + Gigapascal = 9, + Hectopascal = 10, + InchOfMercury = 11, + InchOfWaterColumn = 12, + Kilobar = 13, + KilogramForcePerSquareCentimeter = 14, + KilogramForcePerSquareMeter = 15, + KilogramForcePerSquareMillimeter = 16, + KilonewtonPerSquareCentimeter = 17, + KilonewtonPerSquareMeter = 18, + KilonewtonPerSquareMillimeter = 19, + Kilopascal = 20, + KilopoundForcePerSquareFoot = 21, + KilopoundForcePerSquareInch = 22, + KilopoundForcePerSquareMil = 23, + Megabar = 24, + MeganewtonPerSquareMeter = 25, + Megapascal = 26, + MeterOfElevation = 27, + MeterOfHead = 28, + Microbar = 29, + Micropascal = 30, + Millibar = 31, + MillimeterOfMercury = 32, + MillimeterOfWaterColumn = 33, + Millipascal = 34, + NewtonPerSquareCentimeter = 35, + NewtonPerSquareMeter = 36, + NewtonPerSquareMillimeter = 37, + Pascal = 38, + PoundForcePerSquareFoot = 39, + PoundForcePerSquareInch = 40, + PoundForcePerSquareMil = 41, + PoundPerInchSecondSquared = 42, + TechnicalAtmosphere = 43, + TonneForcePerSquareCentimeter = 44, + TonneForcePerSquareMeter = 45, + TonneForcePerSquareMillimeter = 46, + Torr = 47, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRate.csproj b/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRate.csproj new file mode 100644 index 0000000000..edc39f4c26 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRate.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET PressureChangeRate</Title> + <Description>Adds PressureChangeRate units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>pressurechangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c9e4cfa9-c5d3-5e9d-243c-106ba4b6a447}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.PressureChangeRate</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRate.g.cs b/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRate.g.cs new file mode 100644 index 0000000000..708fb7ea65 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRate.g.cs @@ -0,0 +1,1125 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct PressureChangeRate : IArithmeticQuantity<PressureChangeRate, PressureChangeRateUnit, double>, IEquatable<PressureChangeRate>, IComparable, IComparable<PressureChangeRate>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly PressureChangeRateUnit? _unit; + + static PressureChangeRate() + { + BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + BaseUnit = PressureChangeRateUnit.PascalPerSecond; + Units = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast<PressureChangeRateUnit>().ToArray(); + Zero = new PressureChangeRate(0, BaseUnit); + Info = new QuantityInfo<PressureChangeRateUnit>("PressureChangeRate", + new UnitInfo<PressureChangeRateUnit>[] + { + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.AtmospherePerSecond, "AtmospheresPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.KilopascalPerMinute, "KilopascalsPerMinute", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.KilopascalPerSecond, "KilopascalsPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, "KilopoundsForcePerSquareInchPerMinute", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, "KilopoundsForcePerSquareInchPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.MegapascalPerMinute, "MegapascalsPerMinute", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.MegapascalPerSecond, "MegapascalsPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, "MegapoundsForcePerSquareInchPerMinute", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, "MegapoundsForcePerSquareInchPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, "MillimetersOfMercuryPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.PascalPerMinute, "PascalsPerMinute", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.PascalPerSecond, "PascalsPerSecond", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "PoundsForcePerSquareInchPerMinute", BaseUnits.Undefined), + new UnitInfo<PressureChangeRateUnit>(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "PoundsForcePerSquareInchPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public PressureChangeRate(double value, PressureChangeRateUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="PressureChangeRate" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<PressureChangeRateUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. + /// </summary> + public static PressureChangeRateUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the PressureChangeRate quantity. + /// </summary> + public static PressureChangeRateUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. + /// </summary> + public static PressureChangeRate Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static PressureChangeRate AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<PressureChangeRateUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.AtmospherePerSecond"/> + /// </summary> + public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.KilopascalPerMinute"/> + /// </summary> + public double KilopascalsPerMinute => As(PressureChangeRateUnit.KilopascalPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.KilopascalPerSecond"/> + /// </summary> + public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute"/> + /// </summary> + public double KilopoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond"/> + /// </summary> + public double KilopoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.MegapascalPerMinute"/> + /// </summary> + public double MegapascalsPerMinute => As(PressureChangeRateUnit.MegapascalPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.MegapascalPerSecond"/> + /// </summary> + public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute"/> + /// </summary> + public double MegapoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond"/> + /// </summary> + public double MegapoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.MillimeterOfMercuryPerSecond"/> + /// </summary> + public double MillimetersOfMercuryPerSecond => As(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.PascalPerMinute"/> + /// </summary> + public double PascalsPerMinute => As(PressureChangeRateUnit.PascalPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.PascalPerSecond"/> + /// </summary> + public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.PoundForcePerSquareInchPerMinute"/> + /// </summary> + public double PoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="PressureChangeRateUnit.PoundForcePerSquareInchPerSecond"/> + /// </summary> + public double PoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: PressureChangeRateUnit -> BaseUnit + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.AtmospherePerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.KilopascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.KilopascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.MegapascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.MegapascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> PressureChangeRateUnit + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.AtmospherePerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.AtmospherePerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopascalPerMinute)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapascalPerMinute)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapascalPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillimeterOfMercuryPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MillimeterOfMercuryPerSecond)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerMinute)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute)); + unitConverter.SetConversionFunction<PressureChangeRate>(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.AtmospherePerSecond, new CultureInfo("en-US"), false, true, new string[]{"atm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.AtmospherePerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"атм/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopascalPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kPa/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopascalPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"кПа/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopascalPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kPa/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopascalPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"кПа/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, new CultureInfo("en-US"), false, true, new string[]{"ksi/min", "kipf/in²/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"ksi/мин", "kipf/in²/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, new CultureInfo("en-US"), false, true, new string[]{"ksi/s", "kipf/in²/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"ksi/с", "kipf/in²/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapascalPerMinute, new CultureInfo("en-US"), false, true, new string[]{"MPa/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapascalPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"МПа/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapascalPerSecond, new CultureInfo("en-US"), false, true, new string[]{"MPa/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapascalPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"МПа/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, new CultureInfo("en-US"), false, true, new string[]{"Mpsi/min", "Mlb/in²/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"Мpsi/мин", "Мlb/in²/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Mpsi/s", "Mlb/in²/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"Мpsi/с", "Мlb/in²/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mmHg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"mmHg/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PascalPerMinute, new CultureInfo("en-US"), false, true, new string[]{"Pa/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PascalPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"Па/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PascalPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Pa/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PascalPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"Па/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, new CultureInfo("en-US"), false, true, new string[]{"psi/min", "lb/in²/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"psi/мин", "lb/in²/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, new CultureInfo("en-US"), false, true, new string[]{"psi/s", "lb/in²/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"psi/с", "lb/in²/с"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(PressureChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(PressureChangeRateUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.AtmospherePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) + { + double value = (double) atmospherespersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.KilopascalPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromKilopascalsPerMinute(QuantityValue kilopascalsperminute) + { + double value = (double) kilopascalsperminute; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerMinute); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.KilopascalPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) + { + double value = (double) kilopascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(QuantityValue kilopoundsforcepersquareinchperminute) + { + double value = (double) kilopoundsforcepersquareinchperminute; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(QuantityValue kilopoundsforcepersquareinchpersecond) + { + double value = (double) kilopoundsforcepersquareinchpersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.MegapascalPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromMegapascalsPerMinute(QuantityValue megapascalsperminute) + { + double value = (double) megapascalsperminute; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerMinute); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.MegapascalPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) + { + double value = (double) megapascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(QuantityValue megapoundsforcepersquareinchperminute) + { + double value = (double) megapoundsforcepersquareinchperminute; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(QuantityValue megapoundsforcepersquareinchpersecond) + { + double value = (double) megapoundsforcepersquareinchpersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.MillimeterOfMercuryPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromMillimetersOfMercuryPerSecond(QuantityValue millimetersofmercurypersecond) + { + double value = (double) millimetersofmercurypersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.MillimeterOfMercuryPerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.PascalPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromPascalsPerMinute(QuantityValue pascalsperminute) + { + double value = (double) pascalsperminute; + return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerMinute); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.PascalPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) + { + double value = (double) pascalspersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.PoundForcePerSquareInchPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(QuantityValue poundsforcepersquareinchperminute) + { + double value = (double) poundsforcepersquareinchperminute; + return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); + } + + /// <summary> + /// Creates a <see cref="PressureChangeRate"/> from <see cref="PressureChangeRateUnit.PoundForcePerSquareInchPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(QuantityValue poundsforcepersquareinchpersecond) + { + double value = (double) poundsforcepersquareinchpersecond; + return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="PressureChangeRateUnit" /> to <see cref="PressureChangeRate" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>PressureChangeRate unit value.</returns> + public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) + { + return new PressureChangeRate((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static PressureChangeRate Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static PressureChangeRate Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<PressureChangeRate, PressureChangeRateUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out PressureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out PressureChangeRate result) + { + return QuantityParser.Default.TryParse<PressureChangeRate, PressureChangeRateUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PressureChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static PressureChangeRateUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<PressureChangeRateUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PressureChangeRateUnit)"/> + public static bool TryParseUnit(string str, out PressureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out PressureChangeRateUnit unit) + { + return UnitParser.Default.TryParse<PressureChangeRateUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static PressureChangeRate operator -(PressureChangeRate right) + { + return new PressureChangeRate(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="PressureChangeRate"/> from adding two <see cref="PressureChangeRate"/>.</summary> + public static PressureChangeRate operator +(PressureChangeRate left, PressureChangeRate right) + { + return new PressureChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="PressureChangeRate"/> from subtracting two <see cref="PressureChangeRate"/>.</summary> + public static PressureChangeRate operator -(PressureChangeRate left, PressureChangeRate right) + { + return new PressureChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="PressureChangeRate"/> from multiplying value and <see cref="PressureChangeRate"/>.</summary> + public static PressureChangeRate operator *(double left, PressureChangeRate right) + { + return new PressureChangeRate(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="PressureChangeRate"/> from multiplying value and <see cref="PressureChangeRate"/>.</summary> + public static PressureChangeRate operator *(PressureChangeRate left, double right) + { + return new PressureChangeRate(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="PressureChangeRate"/> from dividing <see cref="PressureChangeRate"/> by value.</summary> + public static PressureChangeRate operator /(PressureChangeRate left, double right) + { + return new PressureChangeRate(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="PressureChangeRate"/> by <see cref="PressureChangeRate"/>.</summary> + public static double operator /(PressureChangeRate left, PressureChangeRate right) + { + return left.PascalsPerSecond / right.PascalsPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(PressureChangeRate left, PressureChangeRate right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(PressureChangeRate left, PressureChangeRate right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(PressureChangeRate left, PressureChangeRate right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(PressureChangeRate left, PressureChangeRate right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="PressureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PressureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(PressureChangeRate left, PressureChangeRate right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="PressureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PressureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(PressureChangeRate left, PressureChangeRate right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PressureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PressureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is PressureChangeRate otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="PressureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(PressureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(PressureChangeRate other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="PressureChangeRate"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is PressureChangeRate otherQuantity)) throw new ArgumentException("Expected type PressureChangeRate.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="PressureChangeRate"/> with another <see cref="PressureChangeRate"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(PressureChangeRate other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another PressureChangeRate within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current PressureChangeRate.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(PressureChangeRateUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is PressureChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A PressureChangeRate with the specified unit.</returns> + public PressureChangeRate ToUnit(PressureChangeRateUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="PressureChangeRate"/> to another <see cref="PressureChangeRate"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A PressureChangeRate with the specified unit.</returns> + public PressureChangeRate ToUnit(PressureChangeRateUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(PressureChangeRate), Unit, typeof(PressureChangeRate), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (PressureChangeRate)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="PressureChangeRate"/> to another <see cref="PressureChangeRate"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="PressureChangeRate"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(PressureChangeRateUnit unit, [NotNullWhen(true)] out PressureChangeRate? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + PressureChangeRate? convertedOrNull = (Unit, unit) switch + { + // PressureChangeRateUnit -> BaseUnit + (PressureChangeRateUnit.AtmospherePerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 1.01325 * 1e5, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.KilopascalPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value / 60) * 1e3d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.KilopascalPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value) * 1e3d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 6.894757293168361e3 / 60) * 1e3d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 6.894757293168361e3) * 1e3d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.MegapascalPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value / 60) * 1e6d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.MegapascalPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value) * 1e6d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 6.894757293168361e3 / 60) * 1e6d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 6.894757293168361e3) * 1e6d, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.MillimeterOfMercuryPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 133.322, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.PascalPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value / 60, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 6.894757293168361e3 / 60, PressureChangeRateUnit.PascalPerSecond), + (PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 6.894757293168361e3, PressureChangeRateUnit.PascalPerSecond), + + // BaseUnit -> PressureChangeRateUnit + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.AtmospherePerSecond) => new PressureChangeRate(_value / (1.01325 * 1e5), PressureChangeRateUnit.AtmospherePerSecond), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerMinute) => new PressureChangeRate((_value * 60) / 1e3d, PressureChangeRateUnit.KilopascalPerMinute), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerSecond) => new PressureChangeRate((_value) / 1e3d, PressureChangeRateUnit.KilopascalPerSecond), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute) => new PressureChangeRate((_value / 6.894757293168361e3 * 60) / 1e3d, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond) => new PressureChangeRate((_value / 6.894757293168361e3) / 1e3d, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerMinute) => new PressureChangeRate((_value * 60) / 1e6d, PressureChangeRateUnit.MegapascalPerMinute), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerSecond) => new PressureChangeRate((_value) / 1e6d, PressureChangeRateUnit.MegapascalPerSecond), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute) => new PressureChangeRate((_value / 6.894757293168361e3 * 60) / 1e6d, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond) => new PressureChangeRate((_value / 6.894757293168361e3) / 1e6d, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillimeterOfMercuryPerSecond) => new PressureChangeRate(_value / 133.322, PressureChangeRateUnit.MillimeterOfMercuryPerSecond), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerMinute) => new PressureChangeRate(_value * 60, PressureChangeRateUnit.PascalPerMinute), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute) => new PressureChangeRate(_value / 6.894757293168361e3 * 60, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute), + (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond) => new PressureChangeRate(_value / 6.894757293168361e3, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is PressureChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<PressureChangeRateUnit> IQuantity<PressureChangeRateUnit>.ToUnit(PressureChangeRateUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<PressureChangeRateUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(PressureChangeRate)) + return this; + else if (conversionType == typeof(PressureChangeRateUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return PressureChangeRate.Info; + else if (conversionType == typeof(BaseDimensions)) + return PressureChangeRate.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRateUnit.g.cs b/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRateUnit.g.cs new file mode 100644 index 0000000000..fed99a6a4a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/PressureChangeRate/PressureChangeRateUnit.g.cs @@ -0,0 +1,45 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PressureChangeRateUnit + { + AtmospherePerSecond = 1, + KilopascalPerMinute = 2, + KilopascalPerSecond = 3, + KilopoundForcePerSquareInchPerMinute = 4, + KilopoundForcePerSquareInchPerSecond = 5, + MegapascalPerMinute = 6, + MegapascalPerSecond = 7, + MegapoundForcePerSquareInchPerMinute = 8, + MegapoundForcePerSquareInchPerSecond = 9, + MillimeterOfMercuryPerSecond = 10, + PascalPerMinute = 11, + PascalPerSecond = 12, + PoundForcePerSquareInchPerMinute = 13, + PoundForcePerSquareInchPerSecond = 14, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Ratio/Ratio.csproj b/UnitsNet.Modular/GeneratedCode/Ratio/Ratio.csproj new file mode 100644 index 0000000000..f651738b75 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Ratio/Ratio.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Ratio</Title> + <Description>Adds Ratio units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>ratio unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{b0be4813-d93e-7b06-d422-23ca28adf22a}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Ratio</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Ratio/Ratio.g.cs b/UnitsNet.Modular/GeneratedCode/Ratio/Ratio.g.cs new file mode 100644 index 0000000000..c4f4ac5614 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Ratio/Ratio.g.cs @@ -0,0 +1,943 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct Ratio : IArithmeticQuantity<Ratio, RatioUnit, double>, IEquatable<Ratio>, IComparable, IComparable<Ratio>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RatioUnit? _unit; + + static Ratio() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = RatioUnit.DecimalFraction; + Units = Enum.GetValues(typeof(RatioUnit)).Cast<RatioUnit>().ToArray(); + Zero = new Ratio(0, BaseUnit); + Info = new QuantityInfo<RatioUnit>("Ratio", + new UnitInfo<RatioUnit>[] + { + new UnitInfo<RatioUnit>(RatioUnit.DecimalFraction, "DecimalFractions", BaseUnits.Undefined), + new UnitInfo<RatioUnit>(RatioUnit.PartPerBillion, "PartsPerBillion", BaseUnits.Undefined), + new UnitInfo<RatioUnit>(RatioUnit.PartPerMillion, "PartsPerMillion", BaseUnits.Undefined), + new UnitInfo<RatioUnit>(RatioUnit.PartPerThousand, "PartsPerThousand", BaseUnits.Undefined), + new UnitInfo<RatioUnit>(RatioUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined), + new UnitInfo<RatioUnit>(RatioUnit.Percent, "Percent", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Ratio(double value, RatioUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Ratio" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RatioUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. + /// </summary> + public static RatioUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Ratio quantity. + /// </summary> + public static RatioUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// </summary> + public static Ratio Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Ratio AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RatioUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Ratio.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioUnit.DecimalFraction"/> + /// </summary> + public double DecimalFractions => As(RatioUnit.DecimalFraction); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioUnit.PartPerBillion"/> + /// </summary> + public double PartsPerBillion => As(RatioUnit.PartPerBillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioUnit.PartPerMillion"/> + /// </summary> + public double PartsPerMillion => As(RatioUnit.PartPerMillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioUnit.PartPerThousand"/> + /// </summary> + public double PartsPerThousand => As(RatioUnit.PartPerThousand); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioUnit.PartPerTrillion"/> + /// </summary> + public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioUnit.Percent"/> + /// </summary> + public double Percent => As(RatioUnit.Percent); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RatioUnit -> BaseUnit + unitConverter.SetConversionFunction<Ratio>(RatioUnit.PartPerBillion, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.PartPerMillion, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.PartPerThousand, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.PartPerTrillion, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.Percent, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Ratio>(RatioUnit.DecimalFraction, RatioUnit.DecimalFraction, quantity => quantity); + + // Register in unit converter: BaseUnit -> RatioUnit + unitConverter.SetConversionFunction<Ratio>(RatioUnit.DecimalFraction, RatioUnit.PartPerBillion, quantity => quantity.ToUnit(RatioUnit.PartPerBillion)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.DecimalFraction, RatioUnit.PartPerMillion, quantity => quantity.ToUnit(RatioUnit.PartPerMillion)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.DecimalFraction, RatioUnit.PartPerThousand, quantity => quantity.ToUnit(RatioUnit.PartPerThousand)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.DecimalFraction, RatioUnit.PartPerTrillion, quantity => quantity.ToUnit(RatioUnit.PartPerTrillion)); + unitConverter.SetConversionFunction<Ratio>(RatioUnit.DecimalFraction, RatioUnit.Percent, quantity => quantity.ToUnit(RatioUnit.Percent)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RatioUnit.DecimalFraction, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(RatioUnit.PartPerBillion, new CultureInfo("en-US"), false, true, new string[]{"ppb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RatioUnit.PartPerMillion, new CultureInfo("en-US"), false, true, new string[]{"ppm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RatioUnit.PartPerThousand, new CultureInfo("en-US"), false, true, new string[]{"‰"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RatioUnit.PartPerTrillion, new CultureInfo("en-US"), false, true, new string[]{"ppt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RatioUnit.Percent, new CultureInfo("en-US"), false, true, new string[]{"%"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RatioUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RatioUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Ratio"/> from <see cref="RatioUnit.DecimalFraction"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Ratio FromDecimalFractions(QuantityValue decimalfractions) + { + double value = (double) decimalfractions; + return new Ratio(value, RatioUnit.DecimalFraction); + } + + /// <summary> + /// Creates a <see cref="Ratio"/> from <see cref="RatioUnit.PartPerBillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) + { + double value = (double) partsperbillion; + return new Ratio(value, RatioUnit.PartPerBillion); + } + + /// <summary> + /// Creates a <see cref="Ratio"/> from <see cref="RatioUnit.PartPerMillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Ratio FromPartsPerMillion(QuantityValue partspermillion) + { + double value = (double) partspermillion; + return new Ratio(value, RatioUnit.PartPerMillion); + } + + /// <summary> + /// Creates a <see cref="Ratio"/> from <see cref="RatioUnit.PartPerThousand"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) + { + double value = (double) partsperthousand; + return new Ratio(value, RatioUnit.PartPerThousand); + } + + /// <summary> + /// Creates a <see cref="Ratio"/> from <see cref="RatioUnit.PartPerTrillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) + { + double value = (double) partspertrillion; + return new Ratio(value, RatioUnit.PartPerTrillion); + } + + /// <summary> + /// Creates a <see cref="Ratio"/> from <see cref="RatioUnit.Percent"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Ratio FromPercent(QuantityValue percent) + { + double value = (double) percent; + return new Ratio(value, RatioUnit.Percent); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RatioUnit" /> to <see cref="Ratio" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Ratio unit value.</returns> + public static Ratio From(QuantityValue value, RatioUnit fromUnit) + { + return new Ratio((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Ratio Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Ratio Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Ratio, RatioUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Ratio result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Ratio result) + { + return QuantityParser.Default.TryParse<Ratio, RatioUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RatioUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RatioUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RatioUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RatioUnit)"/> + public static bool TryParseUnit(string str, out RatioUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RatioUnit unit) + { + return UnitParser.Default.TryParse<RatioUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Ratio operator -(Ratio right) + { + return new Ratio(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Ratio"/> from adding two <see cref="Ratio"/>.</summary> + public static Ratio operator +(Ratio left, Ratio right) + { + return new Ratio(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Ratio"/> from subtracting two <see cref="Ratio"/>.</summary> + public static Ratio operator -(Ratio left, Ratio right) + { + return new Ratio(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Ratio"/> from multiplying value and <see cref="Ratio"/>.</summary> + public static Ratio operator *(double left, Ratio right) + { + return new Ratio(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Ratio"/> from multiplying value and <see cref="Ratio"/>.</summary> + public static Ratio operator *(Ratio left, double right) + { + return new Ratio(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Ratio"/> from dividing <see cref="Ratio"/> by value.</summary> + public static Ratio operator /(Ratio left, double right) + { + return new Ratio(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Ratio"/> by <see cref="Ratio"/>.</summary> + public static double operator /(Ratio left, Ratio right) + { + return left.DecimalFractions / right.DecimalFractions; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Ratio left, Ratio right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Ratio left, Ratio right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Ratio left, Ratio right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Ratio left, Ratio right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Ratio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Ratio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Ratio left, Ratio right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Ratio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Ratio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Ratio left, Ratio right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Ratio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Ratio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Ratio otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Ratio"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Ratio, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Ratio other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Ratio"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Ratio otherQuantity)) throw new ArgumentException("Expected type Ratio.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Ratio"/> with another <see cref="Ratio"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Ratio other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Ratio within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Ratio.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RatioUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RatioUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Ratio to another Ratio with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Ratio with the specified unit.</returns> + public Ratio ToUnit(RatioUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Ratio"/> to another <see cref="Ratio"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Ratio with the specified unit.</returns> + public Ratio ToUnit(RatioUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Ratio), Unit, typeof(Ratio), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Ratio)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Ratio"/> to another <see cref="Ratio"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Ratio"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RatioUnit unit, [NotNullWhen(true)] out Ratio? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Ratio? convertedOrNull = (Unit, unit) switch + { + // RatioUnit -> BaseUnit + (RatioUnit.PartPerBillion, RatioUnit.DecimalFraction) => new Ratio(_value / 1e9, RatioUnit.DecimalFraction), + (RatioUnit.PartPerMillion, RatioUnit.DecimalFraction) => new Ratio(_value / 1e6, RatioUnit.DecimalFraction), + (RatioUnit.PartPerThousand, RatioUnit.DecimalFraction) => new Ratio(_value / 1e3, RatioUnit.DecimalFraction), + (RatioUnit.PartPerTrillion, RatioUnit.DecimalFraction) => new Ratio(_value / 1e12, RatioUnit.DecimalFraction), + (RatioUnit.Percent, RatioUnit.DecimalFraction) => new Ratio(_value / 1e2, RatioUnit.DecimalFraction), + + // BaseUnit -> RatioUnit + (RatioUnit.DecimalFraction, RatioUnit.PartPerBillion) => new Ratio(_value * 1e9, RatioUnit.PartPerBillion), + (RatioUnit.DecimalFraction, RatioUnit.PartPerMillion) => new Ratio(_value * 1e6, RatioUnit.PartPerMillion), + (RatioUnit.DecimalFraction, RatioUnit.PartPerThousand) => new Ratio(_value * 1e3, RatioUnit.PartPerThousand), + (RatioUnit.DecimalFraction, RatioUnit.PartPerTrillion) => new Ratio(_value * 1e12, RatioUnit.PartPerTrillion), + (RatioUnit.DecimalFraction, RatioUnit.Percent) => new Ratio(_value * 1e2, RatioUnit.Percent), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RatioUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RatioUnit> IQuantity<RatioUnit>.ToUnit(RatioUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RatioUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Ratio)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Ratio)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Ratio)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Ratio)) + return this; + else if (conversionType == typeof(RatioUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Ratio.Info; + else if (conversionType == typeof(BaseDimensions)) + return Ratio.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Ratio)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Ratio/RatioUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Ratio/RatioUnit.g.cs new file mode 100644 index 0000000000..32a4540bc5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Ratio/RatioUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RatioUnit + { + DecimalFraction = 1, + PartPerBillion = 2, + PartPerMillion = 3, + PartPerThousand = 4, + PartPerTrillion = 5, + Percent = 6, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRate.csproj b/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRate.csproj new file mode 100644 index 0000000000..8d71c718f7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRate.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET RatioChangeRate</Title> + <Description>Adds RatioChangeRate units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>ratiochangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c028861d-f9e8-8231-2b6a-bc3b3fba349c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.RatioChangeRate</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRate.g.cs b/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRate.g.cs new file mode 100644 index 0000000000..42c16c6fff --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRate.g.cs @@ -0,0 +1,859 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The change in ratio per unit of time. + /// </summary> + [DataContract] + public readonly partial struct RatioChangeRate : IArithmeticQuantity<RatioChangeRate, RatioChangeRateUnit, double>, IEquatable<RatioChangeRate>, IComparable, IComparable<RatioChangeRate>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RatioChangeRateUnit? _unit; + + static RatioChangeRate() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + BaseUnit = RatioChangeRateUnit.DecimalFractionPerSecond; + Units = Enum.GetValues(typeof(RatioChangeRateUnit)).Cast<RatioChangeRateUnit>().ToArray(); + Zero = new RatioChangeRate(0, BaseUnit); + Info = new QuantityInfo<RatioChangeRateUnit>("RatioChangeRate", + new UnitInfo<RatioChangeRateUnit>[] + { + new UnitInfo<RatioChangeRateUnit>(RatioChangeRateUnit.DecimalFractionPerSecond, "DecimalFractionsPerSecond", BaseUnits.Undefined), + new UnitInfo<RatioChangeRateUnit>(RatioChangeRateUnit.PercentPerSecond, "PercentsPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public RatioChangeRate(double value, RatioChangeRateUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="RatioChangeRate" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RatioChangeRateUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of RatioChangeRate, which is DecimalFractionPerSecond. All conversions go via this value. + /// </summary> + public static RatioChangeRateUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the RatioChangeRate quantity. + /// </summary> + public static RatioChangeRateUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFractionPerSecond. + /// </summary> + public static RatioChangeRate Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static RatioChangeRate AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RatioChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RatioChangeRateUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => RatioChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioChangeRateUnit.DecimalFractionPerSecond"/> + /// </summary> + public double DecimalFractionsPerSecond => As(RatioChangeRateUnit.DecimalFractionPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RatioChangeRateUnit.PercentPerSecond"/> + /// </summary> + public double PercentsPerSecond => As(RatioChangeRateUnit.PercentPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RatioChangeRateUnit -> BaseUnit + unitConverter.SetConversionFunction<RatioChangeRate>(RatioChangeRateUnit.PercentPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => quantity.ToUnit(RatioChangeRateUnit.DecimalFractionPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<RatioChangeRate>(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> RatioChangeRateUnit + unitConverter.SetConversionFunction<RatioChangeRate>(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.PercentPerSecond, quantity => quantity.ToUnit(RatioChangeRateUnit.PercentPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RatioChangeRateUnit.DecimalFractionPerSecond, new CultureInfo("en-US"), false, true, new string[]{"/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RatioChangeRateUnit.PercentPerSecond, new CultureInfo("en-US"), false, true, new string[]{"%/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RatioChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RatioChangeRateUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="RatioChangeRate"/> from <see cref="RatioChangeRateUnit.DecimalFractionPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RatioChangeRate FromDecimalFractionsPerSecond(QuantityValue decimalfractionspersecond) + { + double value = (double) decimalfractionspersecond; + return new RatioChangeRate(value, RatioChangeRateUnit.DecimalFractionPerSecond); + } + + /// <summary> + /// Creates a <see cref="RatioChangeRate"/> from <see cref="RatioChangeRateUnit.PercentPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RatioChangeRate FromPercentsPerSecond(QuantityValue percentspersecond) + { + double value = (double) percentspersecond; + return new RatioChangeRate(value, RatioChangeRateUnit.PercentPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RatioChangeRateUnit" /> to <see cref="RatioChangeRate" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>RatioChangeRate unit value.</returns> + public static RatioChangeRate From(QuantityValue value, RatioChangeRateUnit fromUnit) + { + return new RatioChangeRate((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static RatioChangeRate Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static RatioChangeRate Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<RatioChangeRate, RatioChangeRateUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out RatioChangeRate result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out RatioChangeRate result) + { + return QuantityParser.Default.TryParse<RatioChangeRate, RatioChangeRateUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RatioChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RatioChangeRateUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RatioChangeRateUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RatioChangeRateUnit)"/> + public static bool TryParseUnit(string str, out RatioChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RatioChangeRateUnit unit) + { + return UnitParser.Default.TryParse<RatioChangeRateUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static RatioChangeRate operator -(RatioChangeRate right) + { + return new RatioChangeRate(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="RatioChangeRate"/> from adding two <see cref="RatioChangeRate"/>.</summary> + public static RatioChangeRate operator +(RatioChangeRate left, RatioChangeRate right) + { + return new RatioChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RatioChangeRate"/> from subtracting two <see cref="RatioChangeRate"/>.</summary> + public static RatioChangeRate operator -(RatioChangeRate left, RatioChangeRate right) + { + return new RatioChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RatioChangeRate"/> from multiplying value and <see cref="RatioChangeRate"/>.</summary> + public static RatioChangeRate operator *(double left, RatioChangeRate right) + { + return new RatioChangeRate(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="RatioChangeRate"/> from multiplying value and <see cref="RatioChangeRate"/>.</summary> + public static RatioChangeRate operator *(RatioChangeRate left, double right) + { + return new RatioChangeRate(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="RatioChangeRate"/> from dividing <see cref="RatioChangeRate"/> by value.</summary> + public static RatioChangeRate operator /(RatioChangeRate left, double right) + { + return new RatioChangeRate(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="RatioChangeRate"/> by <see cref="RatioChangeRate"/>.</summary> + public static double operator /(RatioChangeRate left, RatioChangeRate right) + { + return left.DecimalFractionsPerSecond / right.DecimalFractionsPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(RatioChangeRate left, RatioChangeRate right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(RatioChangeRate left, RatioChangeRate right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(RatioChangeRate left, RatioChangeRate right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(RatioChangeRate left, RatioChangeRate right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="RatioChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RatioChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(RatioChangeRate left, RatioChangeRate right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="RatioChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RatioChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(RatioChangeRate left, RatioChangeRate right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RatioChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RatioChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is RatioChangeRate otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RatioChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RatioChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(RatioChangeRate other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="RatioChangeRate"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is RatioChangeRate otherQuantity)) throw new ArgumentException("Expected type RatioChangeRate.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="RatioChangeRate"/> with another <see cref="RatioChangeRate"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(RatioChangeRate other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another RatioChangeRate within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(RatioChangeRate other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current RatioChangeRate.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RatioChangeRateUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RatioChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this RatioChangeRate to another RatioChangeRate with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A RatioChangeRate with the specified unit.</returns> + public RatioChangeRate ToUnit(RatioChangeRateUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="RatioChangeRate"/> to another <see cref="RatioChangeRate"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A RatioChangeRate with the specified unit.</returns> + public RatioChangeRate ToUnit(RatioChangeRateUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(RatioChangeRate), Unit, typeof(RatioChangeRate), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (RatioChangeRate)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="RatioChangeRate"/> to another <see cref="RatioChangeRate"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="RatioChangeRate"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RatioChangeRateUnit unit, [NotNullWhen(true)] out RatioChangeRate? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + RatioChangeRate? convertedOrNull = (Unit, unit) switch + { + // RatioChangeRateUnit -> BaseUnit + (RatioChangeRateUnit.PercentPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond) => new RatioChangeRate(_value / 1e2, RatioChangeRateUnit.DecimalFractionPerSecond), + + // BaseUnit -> RatioChangeRateUnit + (RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.PercentPerSecond) => new RatioChangeRate(_value * 1e2, RatioChangeRateUnit.PercentPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RatioChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RatioChangeRateUnit> IQuantity<RatioChangeRateUnit>.ToUnit(RatioChangeRateUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RatioChangeRateUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(RatioChangeRate)) + return this; + else if (conversionType == typeof(RatioChangeRateUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return RatioChangeRate.Info; + else if (conversionType == typeof(BaseDimensions)) + return RatioChangeRate.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRateUnit.g.cs b/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRateUnit.g.cs new file mode 100644 index 0000000000..8537a14a05 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RatioChangeRate/RatioChangeRateUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RatioChangeRateUnit + { + DecimalFractionPerSecond = 1, + PercentPerSecond = 2, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergy.csproj b/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergy.csproj new file mode 100644 index 0000000000..842e7ab846 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ReactiveEnergy</Title> + <Description>Adds ReactiveEnergy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>reactiveenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{64c918a4-27a8-3e9c-e81f-6917f0edde90}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ReactiveEnergy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergy.g.cs b/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergy.g.cs new file mode 100644 index 0000000000..d88a553c57 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergy.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. + /// </summary> + [DataContract] + public readonly partial struct ReactiveEnergy : IArithmeticQuantity<ReactiveEnergy, ReactiveEnergyUnit, double>, IEquatable<ReactiveEnergy>, IComparable, IComparable<ReactiveEnergy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ReactiveEnergyUnit? _unit; + + static ReactiveEnergy() + { + BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); + BaseUnit = ReactiveEnergyUnit.VoltampereReactiveHour; + Units = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast<ReactiveEnergyUnit>().ToArray(); + Zero = new ReactiveEnergy(0, BaseUnit); + Info = new QuantityInfo<ReactiveEnergyUnit>("ReactiveEnergy", + new UnitInfo<ReactiveEnergyUnit>[] + { + new UnitInfo<ReactiveEnergyUnit>(ReactiveEnergyUnit.KilovoltampereReactiveHour, "KilovoltampereReactiveHours", BaseUnits.Undefined), + new UnitInfo<ReactiveEnergyUnit>(ReactiveEnergyUnit.MegavoltampereReactiveHour, "MegavoltampereReactiveHours", BaseUnits.Undefined), + new UnitInfo<ReactiveEnergyUnit>(ReactiveEnergyUnit.VoltampereReactiveHour, "VoltampereReactiveHours", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ReactiveEnergy(double value, ReactiveEnergyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ReactiveEnergy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ReactiveEnergyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. + /// </summary> + public static ReactiveEnergyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ReactiveEnergy quantity. + /// </summary> + public static ReactiveEnergyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. + /// </summary> + public static ReactiveEnergy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ReactiveEnergy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ReactiveEnergyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactiveEnergyUnit.KilovoltampereReactiveHour"/> + /// </summary> + public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactiveEnergyUnit.MegavoltampereReactiveHour"/> + /// </summary> + public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactiveEnergyUnit.VoltampereReactiveHour"/> + /// </summary> + public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ReactiveEnergyUnit -> BaseUnit + unitConverter.SetConversionFunction<ReactiveEnergy>(ReactiveEnergyUnit.KilovoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity.ToUnit(ReactiveEnergyUnit.VoltampereReactiveHour)); + unitConverter.SetConversionFunction<ReactiveEnergy>(ReactiveEnergyUnit.MegavoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity.ToUnit(ReactiveEnergyUnit.VoltampereReactiveHour)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ReactiveEnergy>(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity); + + // Register in unit converter: BaseUnit -> ReactiveEnergyUnit + unitConverter.SetConversionFunction<ReactiveEnergy>(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.KilovoltampereReactiveHour, quantity => quantity.ToUnit(ReactiveEnergyUnit.KilovoltampereReactiveHour)); + unitConverter.SetConversionFunction<ReactiveEnergy>(ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.MegavoltampereReactiveHour, quantity => quantity.ToUnit(ReactiveEnergyUnit.MegavoltampereReactiveHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ReactiveEnergyUnit.KilovoltampereReactiveHour, new CultureInfo("en-US"), false, true, new string[]{"kvarh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReactiveEnergyUnit.MegavoltampereReactiveHour, new CultureInfo("en-US"), false, true, new string[]{"Mvarh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReactiveEnergyUnit.VoltampereReactiveHour, new CultureInfo("en-US"), false, true, new string[]{"varh"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ReactiveEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ReactiveEnergyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ReactiveEnergy"/> from <see cref="ReactiveEnergyUnit.KilovoltampereReactiveHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) + { + double value = (double) kilovoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); + } + + /// <summary> + /// Creates a <see cref="ReactiveEnergy"/> from <see cref="ReactiveEnergyUnit.MegavoltampereReactiveHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) + { + double value = (double) megavoltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); + } + + /// <summary> + /// Creates a <see cref="ReactiveEnergy"/> from <see cref="ReactiveEnergyUnit.VoltampereReactiveHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) + { + double value = (double) voltamperereactivehours; + return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ReactiveEnergyUnit" /> to <see cref="ReactiveEnergy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ReactiveEnergy unit value.</returns> + public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) + { + return new ReactiveEnergy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ReactiveEnergy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ReactiveEnergy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ReactiveEnergy, ReactiveEnergyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ReactiveEnergy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ReactiveEnergy result) + { + return QuantityParser.Default.TryParse<ReactiveEnergy, ReactiveEnergyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReactiveEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ReactiveEnergyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ReactiveEnergyUnit)"/> + public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ReactiveEnergyUnit unit) + { + return UnitParser.Default.TryParse<ReactiveEnergyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ReactiveEnergy operator -(ReactiveEnergy right) + { + return new ReactiveEnergy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReactiveEnergy"/> from adding two <see cref="ReactiveEnergy"/>.</summary> + public static ReactiveEnergy operator +(ReactiveEnergy left, ReactiveEnergy right) + { + return new ReactiveEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReactiveEnergy"/> from subtracting two <see cref="ReactiveEnergy"/>.</summary> + public static ReactiveEnergy operator -(ReactiveEnergy left, ReactiveEnergy right) + { + return new ReactiveEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReactiveEnergy"/> from multiplying value and <see cref="ReactiveEnergy"/>.</summary> + public static ReactiveEnergy operator *(double left, ReactiveEnergy right) + { + return new ReactiveEnergy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReactiveEnergy"/> from multiplying value and <see cref="ReactiveEnergy"/>.</summary> + public static ReactiveEnergy operator *(ReactiveEnergy left, double right) + { + return new ReactiveEnergy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ReactiveEnergy"/> from dividing <see cref="ReactiveEnergy"/> by value.</summary> + public static ReactiveEnergy operator /(ReactiveEnergy left, double right) + { + return new ReactiveEnergy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ReactiveEnergy"/> by <see cref="ReactiveEnergy"/>.</summary> + public static double operator /(ReactiveEnergy left, ReactiveEnergy right) + { + return left.VoltampereReactiveHours / right.VoltampereReactiveHours; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ReactiveEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ReactiveEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReactiveEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ReactiveEnergy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReactiveEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ReactiveEnergy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ReactiveEnergy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ReactiveEnergy otherQuantity)) throw new ArgumentException("Expected type ReactiveEnergy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ReactiveEnergy"/> with another <see cref="ReactiveEnergy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ReactiveEnergy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ReactiveEnergy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ReactiveEnergy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ReactiveEnergyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ReactiveEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ReactiveEnergy with the specified unit.</returns> + public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ReactiveEnergy"/> to another <see cref="ReactiveEnergy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ReactiveEnergy with the specified unit.</returns> + public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ReactiveEnergy), Unit, typeof(ReactiveEnergy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ReactiveEnergy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ReactiveEnergy"/> to another <see cref="ReactiveEnergy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ReactiveEnergy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ReactiveEnergyUnit unit, [NotNullWhen(true)] out ReactiveEnergy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ReactiveEnergy? convertedOrNull = (Unit, unit) switch + { + // ReactiveEnergyUnit -> BaseUnit + (ReactiveEnergyUnit.KilovoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour) => new ReactiveEnergy((_value) * 1e3d, ReactiveEnergyUnit.VoltampereReactiveHour), + (ReactiveEnergyUnit.MegavoltampereReactiveHour, ReactiveEnergyUnit.VoltampereReactiveHour) => new ReactiveEnergy((_value) * 1e6d, ReactiveEnergyUnit.VoltampereReactiveHour), + + // BaseUnit -> ReactiveEnergyUnit + (ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.KilovoltampereReactiveHour) => new ReactiveEnergy((_value) / 1e3d, ReactiveEnergyUnit.KilovoltampereReactiveHour), + (ReactiveEnergyUnit.VoltampereReactiveHour, ReactiveEnergyUnit.MegavoltampereReactiveHour) => new ReactiveEnergy((_value) / 1e6d, ReactiveEnergyUnit.MegavoltampereReactiveHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ReactiveEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ReactiveEnergyUnit> IQuantity<ReactiveEnergyUnit>.ToUnit(ReactiveEnergyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ReactiveEnergyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ReactiveEnergy)) + return this; + else if (conversionType == typeof(ReactiveEnergyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ReactiveEnergy.Info; + else if (conversionType == typeof(BaseDimensions)) + return ReactiveEnergy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergyUnit.g.cs new file mode 100644 index 0000000000..d48f6482a1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReactiveEnergy/ReactiveEnergyUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ReactiveEnergyUnit + { + KilovoltampereReactiveHour = 1, + MegavoltampereReactiveHour = 2, + VoltampereReactiveHour = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePower.csproj b/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePower.csproj new file mode 100644 index 0000000000..3543807cf7 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePower.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ReactivePower</Title> + <Description>Adds ReactivePower units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>reactivepower unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{6821b87e-65eb-bfdb-8fdc-8b183edf739e}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ReactivePower</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePower.g.cs b/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePower.g.cs new file mode 100644 index 0000000000..f430b7a0fc --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePower.g.cs @@ -0,0 +1,901 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct ReactivePower : IArithmeticQuantity<ReactivePower, ReactivePowerUnit, double>, IEquatable<ReactivePower>, IComparable, IComparable<ReactivePower>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ReactivePowerUnit? _unit; + + static ReactivePower() + { + BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + BaseUnit = ReactivePowerUnit.VoltampereReactive; + Units = Enum.GetValues(typeof(ReactivePowerUnit)).Cast<ReactivePowerUnit>().ToArray(); + Zero = new ReactivePower(0, BaseUnit); + Info = new QuantityInfo<ReactivePowerUnit>("ReactivePower", + new UnitInfo<ReactivePowerUnit>[] + { + new UnitInfo<ReactivePowerUnit>(ReactivePowerUnit.GigavoltampereReactive, "GigavoltamperesReactive", BaseUnits.Undefined), + new UnitInfo<ReactivePowerUnit>(ReactivePowerUnit.KilovoltampereReactive, "KilovoltamperesReactive", BaseUnits.Undefined), + new UnitInfo<ReactivePowerUnit>(ReactivePowerUnit.MegavoltampereReactive, "MegavoltamperesReactive", BaseUnits.Undefined), + new UnitInfo<ReactivePowerUnit>(ReactivePowerUnit.VoltampereReactive, "VoltamperesReactive", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ReactivePower(double value, ReactivePowerUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ReactivePower" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ReactivePowerUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ReactivePower, which is VoltampereReactive. All conversions go via this value. + /// </summary> + public static ReactivePowerUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ReactivePower quantity. + /// </summary> + public static ReactivePowerUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. + /// </summary> + public static ReactivePower Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ReactivePower AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ReactivePowerUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ReactivePower.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactivePowerUnit.GigavoltampereReactive"/> + /// </summary> + public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactivePowerUnit.KilovoltampereReactive"/> + /// </summary> + public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactivePowerUnit.MegavoltampereReactive"/> + /// </summary> + public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReactivePowerUnit.VoltampereReactive"/> + /// </summary> + public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ReactivePowerUnit -> BaseUnit + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.GigavoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.VoltampereReactive)); + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.KilovoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.VoltampereReactive)); + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.MegavoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.VoltampereReactive)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.VoltampereReactive, quantity => quantity); + + // Register in unit converter: BaseUnit -> ReactivePowerUnit + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.GigavoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.GigavoltampereReactive)); + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.KilovoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.KilovoltampereReactive)); + unitConverter.SetConversionFunction<ReactivePower>(ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.MegavoltampereReactive, quantity => quantity.ToUnit(ReactivePowerUnit.MegavoltampereReactive)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ReactivePowerUnit.GigavoltampereReactive, new CultureInfo("en-US"), false, true, new string[]{"Gvar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReactivePowerUnit.KilovoltampereReactive, new CultureInfo("en-US"), false, true, new string[]{"kvar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReactivePowerUnit.MegavoltampereReactive, new CultureInfo("en-US"), false, true, new string[]{"Mvar"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReactivePowerUnit.VoltampereReactive, new CultureInfo("en-US"), false, true, new string[]{"var"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ReactivePowerUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ReactivePowerUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ReactivePower"/> from <see cref="ReactivePowerUnit.GigavoltampereReactive"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) + { + double value = (double) gigavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); + } + + /// <summary> + /// Creates a <see cref="ReactivePower"/> from <see cref="ReactivePowerUnit.KilovoltampereReactive"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) + { + double value = (double) kilovoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); + } + + /// <summary> + /// Creates a <see cref="ReactivePower"/> from <see cref="ReactivePowerUnit.MegavoltampereReactive"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) + { + double value = (double) megavoltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); + } + + /// <summary> + /// Creates a <see cref="ReactivePower"/> from <see cref="ReactivePowerUnit.VoltampereReactive"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) + { + double value = (double) voltamperesreactive; + return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ReactivePowerUnit" /> to <see cref="ReactivePower" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ReactivePower unit value.</returns> + public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) + { + return new ReactivePower((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ReactivePower Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ReactivePower Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ReactivePower, ReactivePowerUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ReactivePower result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ReactivePower result) + { + return QuantityParser.Default.TryParse<ReactivePower, ReactivePowerUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReactivePowerUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReactivePowerUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ReactivePowerUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ReactivePowerUnit)"/> + public static bool TryParseUnit(string str, out ReactivePowerUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ReactivePowerUnit unit) + { + return UnitParser.Default.TryParse<ReactivePowerUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ReactivePower operator -(ReactivePower right) + { + return new ReactivePower(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReactivePower"/> from adding two <see cref="ReactivePower"/>.</summary> + public static ReactivePower operator +(ReactivePower left, ReactivePower right) + { + return new ReactivePower(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReactivePower"/> from subtracting two <see cref="ReactivePower"/>.</summary> + public static ReactivePower operator -(ReactivePower left, ReactivePower right) + { + return new ReactivePower(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReactivePower"/> from multiplying value and <see cref="ReactivePower"/>.</summary> + public static ReactivePower operator *(double left, ReactivePower right) + { + return new ReactivePower(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReactivePower"/> from multiplying value and <see cref="ReactivePower"/>.</summary> + public static ReactivePower operator *(ReactivePower left, double right) + { + return new ReactivePower(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ReactivePower"/> from dividing <see cref="ReactivePower"/> by value.</summary> + public static ReactivePower operator /(ReactivePower left, double right) + { + return new ReactivePower(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ReactivePower"/> by <see cref="ReactivePower"/>.</summary> + public static double operator /(ReactivePower left, ReactivePower right) + { + return left.VoltamperesReactive / right.VoltamperesReactive; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ReactivePower left, ReactivePower right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ReactivePower left, ReactivePower right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ReactivePower left, ReactivePower right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ReactivePower left, ReactivePower right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ReactivePower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactivePower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ReactivePower left, ReactivePower right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ReactivePower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactivePower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ReactivePower left, ReactivePower right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReactivePower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactivePower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ReactivePower otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReactivePower"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReactivePower, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ReactivePower other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ReactivePower"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ReactivePower otherQuantity)) throw new ArgumentException("Expected type ReactivePower.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ReactivePower"/> with another <see cref="ReactivePower"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ReactivePower other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ReactivePower within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ReactivePower.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ReactivePowerUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ReactivePowerUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ReactivePower to another ReactivePower with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ReactivePower with the specified unit.</returns> + public ReactivePower ToUnit(ReactivePowerUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ReactivePower"/> to another <see cref="ReactivePower"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ReactivePower with the specified unit.</returns> + public ReactivePower ToUnit(ReactivePowerUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ReactivePower), Unit, typeof(ReactivePower), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ReactivePower)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ReactivePower"/> to another <see cref="ReactivePower"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ReactivePower"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ReactivePowerUnit unit, [NotNullWhen(true)] out ReactivePower? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ReactivePower? convertedOrNull = (Unit, unit) switch + { + // ReactivePowerUnit -> BaseUnit + (ReactivePowerUnit.GigavoltampereReactive, ReactivePowerUnit.VoltampereReactive) => new ReactivePower((_value) * 1e9d, ReactivePowerUnit.VoltampereReactive), + (ReactivePowerUnit.KilovoltampereReactive, ReactivePowerUnit.VoltampereReactive) => new ReactivePower((_value) * 1e3d, ReactivePowerUnit.VoltampereReactive), + (ReactivePowerUnit.MegavoltampereReactive, ReactivePowerUnit.VoltampereReactive) => new ReactivePower((_value) * 1e6d, ReactivePowerUnit.VoltampereReactive), + + // BaseUnit -> ReactivePowerUnit + (ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.GigavoltampereReactive) => new ReactivePower((_value) / 1e9d, ReactivePowerUnit.GigavoltampereReactive), + (ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.KilovoltampereReactive) => new ReactivePower((_value) / 1e3d, ReactivePowerUnit.KilovoltampereReactive), + (ReactivePowerUnit.VoltampereReactive, ReactivePowerUnit.MegavoltampereReactive) => new ReactivePower((_value) / 1e6d, ReactivePowerUnit.MegavoltampereReactive), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ReactivePowerUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactivePowerUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ReactivePowerUnit> IQuantity<ReactivePowerUnit>.ToUnit(ReactivePowerUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ReactivePowerUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReactivePower)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReactivePower)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReactivePower)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ReactivePower)) + return this; + else if (conversionType == typeof(ReactivePowerUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ReactivePower.Info; + else if (conversionType == typeof(BaseDimensions)) + return ReactivePower.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ReactivePower)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePowerUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePowerUnit.g.cs new file mode 100644 index 0000000000..32e7a9ede9 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReactivePower/ReactivePowerUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ReactivePowerUnit + { + GigavoltampereReactive = 1, + KilovoltampereReactive = 2, + MegavoltampereReactive = 3, + VoltampereReactive = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalArea.csproj b/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalArea.csproj new file mode 100644 index 0000000000..14485b07a6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalArea.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ReciprocalArea</Title> + <Description>Adds ReciprocalArea units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>reciprocalarea unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{30fee563-a3f0-9c50-bfd1-1af707aaf3c4}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ReciprocalArea</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalArea.g.cs b/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalArea.g.cs new file mode 100644 index 0000000000..165651c6f5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalArea.g.cs @@ -0,0 +1,1051 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Reciprocal area (Inverse-square) quantity is used to specify a physical quantity inversely proportional to the square of the distance. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Inverse-square_law + /// </remarks> + [DataContract] + public readonly partial struct ReciprocalArea : IArithmeticQuantity<ReciprocalArea, ReciprocalAreaUnit, double>, IEquatable<ReciprocalArea>, IComparable, IComparable<ReciprocalArea>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ReciprocalAreaUnit? _unit; + + static ReciprocalArea() + { + BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); + BaseUnit = ReciprocalAreaUnit.InverseSquareMeter; + Units = Enum.GetValues(typeof(ReciprocalAreaUnit)).Cast<ReciprocalAreaUnit>().ToArray(); + Zero = new ReciprocalArea(0, BaseUnit); + Info = new QuantityInfo<ReciprocalAreaUnit>("ReciprocalArea", + new UnitInfo<ReciprocalAreaUnit>[] + { + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareCentimeter, "InverseSquareCentimeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareDecimeter, "InverseSquareDecimeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareFoot, "InverseSquareFeet", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareInch, "InverseSquareInches", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareKilometer, "InverseSquareKilometers", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareMeter, "InverseSquareMeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareMicrometer, "InverseSquareMicrometers", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareMile, "InverseSquareMiles", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareMillimeter, "InverseSquareMillimeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseSquareYard, "InverseSquareYards", BaseUnits.Undefined), + new UnitInfo<ReciprocalAreaUnit>(ReciprocalAreaUnit.InverseUsSurveySquareFoot, "InverseUsSurveySquareFeet", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ReciprocalArea(double value, ReciprocalAreaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ReciprocalArea" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ReciprocalAreaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ReciprocalArea, which is InverseSquareMeter. All conversions go via this value. + /// </summary> + public static ReciprocalAreaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ReciprocalArea quantity. + /// </summary> + public static ReciprocalAreaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit InverseSquareMeter. + /// </summary> + public static ReciprocalArea Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ReciprocalArea AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ReciprocalAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ReciprocalAreaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ReciprocalArea.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareCentimeter"/> + /// </summary> + public double InverseSquareCentimeters => As(ReciprocalAreaUnit.InverseSquareCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareDecimeter"/> + /// </summary> + public double InverseSquareDecimeters => As(ReciprocalAreaUnit.InverseSquareDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareFoot"/> + /// </summary> + public double InverseSquareFeet => As(ReciprocalAreaUnit.InverseSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareInch"/> + /// </summary> + public double InverseSquareInches => As(ReciprocalAreaUnit.InverseSquareInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareKilometer"/> + /// </summary> + public double InverseSquareKilometers => As(ReciprocalAreaUnit.InverseSquareKilometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareMeter"/> + /// </summary> + public double InverseSquareMeters => As(ReciprocalAreaUnit.InverseSquareMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareMicrometer"/> + /// </summary> + public double InverseSquareMicrometers => As(ReciprocalAreaUnit.InverseSquareMicrometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareMile"/> + /// </summary> + public double InverseSquareMiles => As(ReciprocalAreaUnit.InverseSquareMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareMillimeter"/> + /// </summary> + public double InverseSquareMillimeters => As(ReciprocalAreaUnit.InverseSquareMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseSquareYard"/> + /// </summary> + public double InverseSquareYards => As(ReciprocalAreaUnit.InverseSquareYard); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalAreaUnit.InverseUsSurveySquareFoot"/> + /// </summary> + public double InverseUsSurveySquareFeet => As(ReciprocalAreaUnit.InverseUsSurveySquareFoot); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ReciprocalAreaUnit -> BaseUnit + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareCentimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareDecimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareInch, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareKilometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMicrometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMile, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMillimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareYard, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseUsSurveySquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ReciprocalAreaUnit + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareCentimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareCentimeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareDecimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareDecimeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareFoot, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareFoot)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareInch, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareInch)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareKilometer, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareKilometer)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMicrometer, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMicrometer)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMile, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMile)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMillimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMillimeter)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareYard, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareYard)); + unitConverter.SetConversionFunction<ReciprocalArea>(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseUsSurveySquareFoot, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseUsSurveySquareFoot)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareDecimeter, new CultureInfo("en-US"), false, true, new string[]{"dm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"ft⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareInch, new CultureInfo("en-US"), false, true, new string[]{"in⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareKilometer, new CultureInfo("en-US"), false, true, new string[]{"km⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"m⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareMicrometer, new CultureInfo("en-US"), false, true, new string[]{"µm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareMile, new CultureInfo("en-US"), false, true, new string[]{"mi⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mm⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseSquareYard, new CultureInfo("en-US"), false, true, new string[]{"yd⁻²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalAreaUnit.InverseUsSurveySquareFoot, new CultureInfo("en-US"), false, true, new string[]{"ft⁻² (US)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ReciprocalAreaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ReciprocalAreaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareCentimeters(QuantityValue inversesquarecentimeters) + { + double value = (double) inversesquarecentimeters; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareCentimeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareDecimeters(QuantityValue inversesquaredecimeters) + { + double value = (double) inversesquaredecimeters; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareDecimeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareFeet(QuantityValue inversesquarefeet) + { + double value = (double) inversesquarefeet; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareFoot); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareInches(QuantityValue inversesquareinches) + { + double value = (double) inversesquareinches; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareInch); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareKilometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareKilometers(QuantityValue inversesquarekilometers) + { + double value = (double) inversesquarekilometers; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareKilometer); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareMeters(QuantityValue inversesquaremeters) + { + double value = (double) inversesquaremeters; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareMicrometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareMicrometers(QuantityValue inversesquaremicrometers) + { + double value = (double) inversesquaremicrometers; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMicrometer); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareMiles(QuantityValue inversesquaremiles) + { + double value = (double) inversesquaremiles; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMile); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareMillimeters(QuantityValue inversesquaremillimeters) + { + double value = (double) inversesquaremillimeters; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMillimeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseSquareYard"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseSquareYards(QuantityValue inversesquareyards) + { + double value = (double) inversesquareyards; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareYard); + } + + /// <summary> + /// Creates a <see cref="ReciprocalArea"/> from <see cref="ReciprocalAreaUnit.InverseUsSurveySquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalArea FromInverseUsSurveySquareFeet(QuantityValue inverseussurveysquarefeet) + { + double value = (double) inverseussurveysquarefeet; + return new ReciprocalArea(value, ReciprocalAreaUnit.InverseUsSurveySquareFoot); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ReciprocalAreaUnit" /> to <see cref="ReciprocalArea" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ReciprocalArea unit value.</returns> + public static ReciprocalArea From(QuantityValue value, ReciprocalAreaUnit fromUnit) + { + return new ReciprocalArea((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ReciprocalArea Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ReciprocalArea Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ReciprocalArea, ReciprocalAreaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ReciprocalArea result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ReciprocalArea result) + { + return QuantityParser.Default.TryParse<ReciprocalArea, ReciprocalAreaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReciprocalAreaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReciprocalAreaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ReciprocalAreaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ReciprocalAreaUnit)"/> + public static bool TryParseUnit(string str, out ReciprocalAreaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ReciprocalAreaUnit unit) + { + return UnitParser.Default.TryParse<ReciprocalAreaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ReciprocalArea operator -(ReciprocalArea right) + { + return new ReciprocalArea(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReciprocalArea"/> from adding two <see cref="ReciprocalArea"/>.</summary> + public static ReciprocalArea operator +(ReciprocalArea left, ReciprocalArea right) + { + return new ReciprocalArea(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReciprocalArea"/> from subtracting two <see cref="ReciprocalArea"/>.</summary> + public static ReciprocalArea operator -(ReciprocalArea left, ReciprocalArea right) + { + return new ReciprocalArea(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReciprocalArea"/> from multiplying value and <see cref="ReciprocalArea"/>.</summary> + public static ReciprocalArea operator *(double left, ReciprocalArea right) + { + return new ReciprocalArea(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReciprocalArea"/> from multiplying value and <see cref="ReciprocalArea"/>.</summary> + public static ReciprocalArea operator *(ReciprocalArea left, double right) + { + return new ReciprocalArea(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ReciprocalArea"/> from dividing <see cref="ReciprocalArea"/> by value.</summary> + public static ReciprocalArea operator /(ReciprocalArea left, double right) + { + return new ReciprocalArea(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ReciprocalArea"/> by <see cref="ReciprocalArea"/>.</summary> + public static double operator /(ReciprocalArea left, ReciprocalArea right) + { + return left.InverseSquareMeters / right.InverseSquareMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ReciprocalArea left, ReciprocalArea right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ReciprocalArea left, ReciprocalArea right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ReciprocalArea left, ReciprocalArea right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ReciprocalArea left, ReciprocalArea right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ReciprocalArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ReciprocalArea left, ReciprocalArea right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ReciprocalArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ReciprocalArea left, ReciprocalArea right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReciprocalArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ReciprocalArea otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReciprocalArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ReciprocalArea other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ReciprocalArea"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ReciprocalArea otherQuantity)) throw new ArgumentException("Expected type ReciprocalArea.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ReciprocalArea"/> with another <see cref="ReciprocalArea"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ReciprocalArea other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ReciprocalArea within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(ReciprocalArea other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ReciprocalArea.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ReciprocalAreaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ReciprocalAreaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ReciprocalArea to another ReciprocalArea with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ReciprocalArea with the specified unit.</returns> + public ReciprocalArea ToUnit(ReciprocalAreaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ReciprocalArea"/> to another <see cref="ReciprocalArea"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ReciprocalArea with the specified unit.</returns> + public ReciprocalArea ToUnit(ReciprocalAreaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ReciprocalArea), Unit, typeof(ReciprocalArea), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ReciprocalArea)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ReciprocalArea"/> to another <see cref="ReciprocalArea"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ReciprocalArea"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ReciprocalAreaUnit unit, [NotNullWhen(true)] out ReciprocalArea? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ReciprocalArea? convertedOrNull = (Unit, unit) switch + { + // ReciprocalAreaUnit -> BaseUnit + (ReciprocalAreaUnit.InverseSquareCentimeter, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-4, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareDecimeter, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-2, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareFoot, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 0.092903, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareInch, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 0.00064516, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareKilometer, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e6, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareMicrometer, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-12, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareMile, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 2.59e6, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareMillimeter, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-6, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseSquareYard, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 0.836127, ReciprocalAreaUnit.InverseSquareMeter), + (ReciprocalAreaUnit.InverseUsSurveySquareFoot, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 0.09290341161, ReciprocalAreaUnit.InverseSquareMeter), + + // BaseUnit -> ReciprocalAreaUnit + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareCentimeter) => new ReciprocalArea(_value * 1e-4, ReciprocalAreaUnit.InverseSquareCentimeter), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareDecimeter) => new ReciprocalArea(_value * 1e-2, ReciprocalAreaUnit.InverseSquareDecimeter), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareFoot) => new ReciprocalArea(_value * 0.092903, ReciprocalAreaUnit.InverseSquareFoot), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareInch) => new ReciprocalArea(_value * 0.00064516, ReciprocalAreaUnit.InverseSquareInch), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareKilometer) => new ReciprocalArea(_value * 1e6, ReciprocalAreaUnit.InverseSquareKilometer), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMicrometer) => new ReciprocalArea(_value * 1e-12, ReciprocalAreaUnit.InverseSquareMicrometer), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMile) => new ReciprocalArea(_value * 2.59e6, ReciprocalAreaUnit.InverseSquareMile), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMillimeter) => new ReciprocalArea(_value * 1e-6, ReciprocalAreaUnit.InverseSquareMillimeter), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareYard) => new ReciprocalArea(_value * 0.836127, ReciprocalAreaUnit.InverseSquareYard), + (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseUsSurveySquareFoot) => new ReciprocalArea(_value * 0.09290341161, ReciprocalAreaUnit.InverseUsSurveySquareFoot), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ReciprocalAreaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ReciprocalAreaUnit> IQuantity<ReciprocalAreaUnit>.ToUnit(ReciprocalAreaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ReciprocalAreaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ReciprocalArea)) + return this; + else if (conversionType == typeof(ReciprocalAreaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ReciprocalArea.Info; + else if (conversionType == typeof(BaseDimensions)) + return ReciprocalArea.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalAreaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalAreaUnit.g.cs new file mode 100644 index 0000000000..a1263b27b9 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReciprocalArea/ReciprocalAreaUnit.g.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ReciprocalAreaUnit + { + InverseSquareCentimeter = 1, + InverseSquareDecimeter = 2, + InverseSquareFoot = 3, + InverseSquareInch = 4, + InverseSquareKilometer = 5, + InverseSquareMeter = 6, + InverseSquareMicrometer = 7, + InverseSquareMile = 8, + InverseSquareMillimeter = 9, + InverseSquareYard = 10, + InverseUsSurveySquareFoot = 11, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLength.csproj b/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLength.csproj new file mode 100644 index 0000000000..e31bcb857c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLength.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ReciprocalLength</Title> + <Description>Adds ReciprocalLength units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>reciprocallength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{83d6c79a-c71a-d467-284c-28edbbd059d2}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ReciprocalLength</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLength.g.cs b/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLength.g.cs new file mode 100644 index 0000000000..2d196d54d2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLength.g.cs @@ -0,0 +1,1030 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Reciprocal (Inverse) Length is used in various fields of science and mathematics. It is defined as the inverse value of a length unit. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Reciprocal_length + /// </remarks> + [DataContract] + public readonly partial struct ReciprocalLength : IArithmeticQuantity<ReciprocalLength, ReciprocalLengthUnit, double>, IEquatable<ReciprocalLength>, IComparable, IComparable<ReciprocalLength>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ReciprocalLengthUnit? _unit; + + static ReciprocalLength() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 0, 0, 0); + BaseUnit = ReciprocalLengthUnit.InverseMeter; + Units = Enum.GetValues(typeof(ReciprocalLengthUnit)).Cast<ReciprocalLengthUnit>().ToArray(); + Zero = new ReciprocalLength(0, BaseUnit); + Info = new QuantityInfo<ReciprocalLengthUnit>("ReciprocalLength", + new UnitInfo<ReciprocalLengthUnit>[] + { + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseCentimeter, "InverseCentimeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseFoot, "InverseFeet", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseInch, "InverseInches", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseMeter, "InverseMeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseMicroinch, "InverseMicroinches", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseMil, "InverseMils", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseMile, "InverseMiles", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseMillimeter, "InverseMillimeters", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseUsSurveyFoot, "InverseUsSurveyFeet", BaseUnits.Undefined), + new UnitInfo<ReciprocalLengthUnit>(ReciprocalLengthUnit.InverseYard, "InverseYards", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ReciprocalLength(double value, ReciprocalLengthUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ReciprocalLength" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ReciprocalLengthUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ReciprocalLength, which is InverseMeter. All conversions go via this value. + /// </summary> + public static ReciprocalLengthUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ReciprocalLength quantity. + /// </summary> + public static ReciprocalLengthUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit InverseMeter. + /// </summary> + public static ReciprocalLength Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ReciprocalLength AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ReciprocalLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ReciprocalLengthUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ReciprocalLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseCentimeter"/> + /// </summary> + public double InverseCentimeters => As(ReciprocalLengthUnit.InverseCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseFoot"/> + /// </summary> + public double InverseFeet => As(ReciprocalLengthUnit.InverseFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseInch"/> + /// </summary> + public double InverseInches => As(ReciprocalLengthUnit.InverseInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseMeter"/> + /// </summary> + public double InverseMeters => As(ReciprocalLengthUnit.InverseMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseMicroinch"/> + /// </summary> + public double InverseMicroinches => As(ReciprocalLengthUnit.InverseMicroinch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseMil"/> + /// </summary> + public double InverseMils => As(ReciprocalLengthUnit.InverseMil); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseMile"/> + /// </summary> + public double InverseMiles => As(ReciprocalLengthUnit.InverseMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseMillimeter"/> + /// </summary> + public double InverseMillimeters => As(ReciprocalLengthUnit.InverseMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseUsSurveyFoot"/> + /// </summary> + public double InverseUsSurveyFeet => As(ReciprocalLengthUnit.InverseUsSurveyFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ReciprocalLengthUnit.InverseYard"/> + /// </summary> + public double InverseYards => As(ReciprocalLengthUnit.InverseYard); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ReciprocalLengthUnit -> BaseUnit + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseCentimeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseFoot, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseInch, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMicroinch, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMil, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMile, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMillimeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseUsSurveyFoot, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseYard, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> ReciprocalLengthUnit + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseCentimeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseCentimeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseFoot, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseFoot)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseInch, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseInch)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMicroinch, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMicroinch)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMil, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMil)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMile, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMile)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMillimeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMillimeter)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseUsSurveyFoot, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseUsSurveyFoot)); + unitConverter.SetConversionFunction<ReciprocalLength>(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseYard, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseYard)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cm⁻¹", "1/cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseFoot, new CultureInfo("en-US"), false, true, new string[]{"ft⁻¹", "1/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseInch, new CultureInfo("en-US"), false, true, new string[]{"in⁻¹", "1/in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseMeter, new CultureInfo("en-US"), false, true, new string[]{"m⁻¹", "1/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseMicroinch, new CultureInfo("en-US"), false, true, new string[]{"µin⁻¹", "1/µin"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseMil, new CultureInfo("en-US"), false, true, new string[]{"mil⁻¹", "1/mil"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseMile, new CultureInfo("en-US"), false, true, new string[]{"mi⁻¹", "1/mi"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mm⁻¹", "1/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseUsSurveyFoot, new CultureInfo("en-US"), false, true, new string[]{"ftUS⁻¹", "1/ftUS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ReciprocalLengthUnit.InverseYard, new CultureInfo("en-US"), false, true, new string[]{"yd⁻¹", "1/yd"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ReciprocalLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ReciprocalLengthUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseCentimeters(QuantityValue inversecentimeters) + { + double value = (double) inversecentimeters; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseCentimeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseFeet(QuantityValue inversefeet) + { + double value = (double) inversefeet; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseFoot); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseInches(QuantityValue inverseinches) + { + double value = (double) inverseinches; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseInch); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseMeters(QuantityValue inversemeters) + { + double value = (double) inversemeters; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseMicroinch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseMicroinches(QuantityValue inversemicroinches) + { + double value = (double) inversemicroinches; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMicroinch); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseMil"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseMils(QuantityValue inversemils) + { + double value = (double) inversemils; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMil); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseMiles(QuantityValue inversemiles) + { + double value = (double) inversemiles; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMile); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseMillimeters(QuantityValue inversemillimeters) + { + double value = (double) inversemillimeters; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMillimeter); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseUsSurveyFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseUsSurveyFeet(QuantityValue inverseussurveyfeet) + { + double value = (double) inverseussurveyfeet; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseUsSurveyFoot); + } + + /// <summary> + /// Creates a <see cref="ReciprocalLength"/> from <see cref="ReciprocalLengthUnit.InverseYard"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ReciprocalLength FromInverseYards(QuantityValue inverseyards) + { + double value = (double) inverseyards; + return new ReciprocalLength(value, ReciprocalLengthUnit.InverseYard); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ReciprocalLengthUnit" /> to <see cref="ReciprocalLength" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ReciprocalLength unit value.</returns> + public static ReciprocalLength From(QuantityValue value, ReciprocalLengthUnit fromUnit) + { + return new ReciprocalLength((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ReciprocalLength Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ReciprocalLength Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ReciprocalLength, ReciprocalLengthUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ReciprocalLength result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ReciprocalLength result) + { + return QuantityParser.Default.TryParse<ReciprocalLength, ReciprocalLengthUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReciprocalLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ReciprocalLengthUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ReciprocalLengthUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ReciprocalLengthUnit)"/> + public static bool TryParseUnit(string str, out ReciprocalLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ReciprocalLengthUnit unit) + { + return UnitParser.Default.TryParse<ReciprocalLengthUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ReciprocalLength operator -(ReciprocalLength right) + { + return new ReciprocalLength(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReciprocalLength"/> from adding two <see cref="ReciprocalLength"/>.</summary> + public static ReciprocalLength operator +(ReciprocalLength left, ReciprocalLength right) + { + return new ReciprocalLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReciprocalLength"/> from subtracting two <see cref="ReciprocalLength"/>.</summary> + public static ReciprocalLength operator -(ReciprocalLength left, ReciprocalLength right) + { + return new ReciprocalLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ReciprocalLength"/> from multiplying value and <see cref="ReciprocalLength"/>.</summary> + public static ReciprocalLength operator *(double left, ReciprocalLength right) + { + return new ReciprocalLength(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ReciprocalLength"/> from multiplying value and <see cref="ReciprocalLength"/>.</summary> + public static ReciprocalLength operator *(ReciprocalLength left, double right) + { + return new ReciprocalLength(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ReciprocalLength"/> from dividing <see cref="ReciprocalLength"/> by value.</summary> + public static ReciprocalLength operator /(ReciprocalLength left, double right) + { + return new ReciprocalLength(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ReciprocalLength"/> by <see cref="ReciprocalLength"/>.</summary> + public static double operator /(ReciprocalLength left, ReciprocalLength right) + { + return left.InverseMeters / right.InverseMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ReciprocalLength left, ReciprocalLength right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ReciprocalLength left, ReciprocalLength right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ReciprocalLength left, ReciprocalLength right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ReciprocalLength left, ReciprocalLength right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ReciprocalLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ReciprocalLength left, ReciprocalLength right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ReciprocalLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ReciprocalLength left, ReciprocalLength right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReciprocalLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ReciprocalLength otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ReciprocalLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ReciprocalLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ReciprocalLength other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ReciprocalLength"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ReciprocalLength otherQuantity)) throw new ArgumentException("Expected type ReciprocalLength.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ReciprocalLength"/> with another <see cref="ReciprocalLength"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ReciprocalLength other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ReciprocalLength within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(ReciprocalLength other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ReciprocalLength.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ReciprocalLengthUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ReciprocalLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ReciprocalLength to another ReciprocalLength with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ReciprocalLength with the specified unit.</returns> + public ReciprocalLength ToUnit(ReciprocalLengthUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ReciprocalLength"/> to another <see cref="ReciprocalLength"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ReciprocalLength with the specified unit.</returns> + public ReciprocalLength ToUnit(ReciprocalLengthUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ReciprocalLength), Unit, typeof(ReciprocalLength), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ReciprocalLength)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ReciprocalLength"/> to another <see cref="ReciprocalLength"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ReciprocalLength"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ReciprocalLengthUnit unit, [NotNullWhen(true)] out ReciprocalLength? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ReciprocalLength? convertedOrNull = (Unit, unit) switch + { + // ReciprocalLengthUnit -> BaseUnit + (ReciprocalLengthUnit.InverseCentimeter, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value * 1e2, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseFoot, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 0.3048, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseInch, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 2.54e-2, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseMicroinch, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 2.54e-8, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseMil, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 2.54e-5, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseMile, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 1609.34, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseMillimeter, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value * 1e3, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseUsSurveyFoot, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value * 3937 / 1200, ReciprocalLengthUnit.InverseMeter), + (ReciprocalLengthUnit.InverseYard, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 0.9144, ReciprocalLengthUnit.InverseMeter), + + // BaseUnit -> ReciprocalLengthUnit + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseCentimeter) => new ReciprocalLength(_value / 1e2, ReciprocalLengthUnit.InverseCentimeter), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseFoot) => new ReciprocalLength(_value * 0.3048, ReciprocalLengthUnit.InverseFoot), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseInch) => new ReciprocalLength(_value * 2.54e-2, ReciprocalLengthUnit.InverseInch), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMicroinch) => new ReciprocalLength(_value * 2.54e-8, ReciprocalLengthUnit.InverseMicroinch), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMil) => new ReciprocalLength(_value * 2.54e-5, ReciprocalLengthUnit.InverseMil), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMile) => new ReciprocalLength(_value * 1609.34, ReciprocalLengthUnit.InverseMile), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMillimeter) => new ReciprocalLength(_value / 1e3, ReciprocalLengthUnit.InverseMillimeter), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseUsSurveyFoot) => new ReciprocalLength(_value * 1200 / 3937, ReciprocalLengthUnit.InverseUsSurveyFoot), + (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseYard) => new ReciprocalLength(_value * 0.9144, ReciprocalLengthUnit.InverseYard), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ReciprocalLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ReciprocalLengthUnit> IQuantity<ReciprocalLengthUnit>.ToUnit(ReciprocalLengthUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ReciprocalLengthUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ReciprocalLength)) + return this; + else if (conversionType == typeof(ReciprocalLengthUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ReciprocalLength.Info; + else if (conversionType == typeof(BaseDimensions)) + return ReciprocalLength.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLengthUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLengthUnit.g.cs new file mode 100644 index 0000000000..fb9d93700c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ReciprocalLength/ReciprocalLengthUnit.g.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ReciprocalLengthUnit + { + InverseCentimeter = 1, + InverseFoot = 2, + InverseInch = 3, + InverseMeter = 4, + InverseMicroinch = 5, + InverseMil = 6, + InverseMile = 7, + InverseMillimeter = 8, + InverseUsSurveyFoot = 9, + InverseYard = 10, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidity.csproj b/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidity.csproj new file mode 100644 index 0000000000..6ed1cb65d3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET RelativeHumidity</Title> + <Description>Adds RelativeHumidity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>relativehumidity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{4ac05c74-08c5-2153-f38c-976975747b5c}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.RelativeHumidity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidity.g.cs b/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidity.g.cs new file mode 100644 index 0000000000..595fd56661 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidity.g.cs @@ -0,0 +1,838 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Relative humidity is a ratio of the actual water vapor present in the air to the maximum water vapor in the air at the given temperature. + /// </summary> + [DataContract] + public readonly partial struct RelativeHumidity : IArithmeticQuantity<RelativeHumidity, RelativeHumidityUnit, double>, IEquatable<RelativeHumidity>, IComparable, IComparable<RelativeHumidity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RelativeHumidityUnit? _unit; + + static RelativeHumidity() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = RelativeHumidityUnit.Percent; + Units = Enum.GetValues(typeof(RelativeHumidityUnit)).Cast<RelativeHumidityUnit>().ToArray(); + Zero = new RelativeHumidity(0, BaseUnit); + Info = new QuantityInfo<RelativeHumidityUnit>("RelativeHumidity", + new UnitInfo<RelativeHumidityUnit>[] + { + new UnitInfo<RelativeHumidityUnit>(RelativeHumidityUnit.Percent, "Percent", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public RelativeHumidity(double value, RelativeHumidityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="RelativeHumidity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RelativeHumidityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of RelativeHumidity, which is Percent. All conversions go via this value. + /// </summary> + public static RelativeHumidityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the RelativeHumidity quantity. + /// </summary> + public static RelativeHumidityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Percent. + /// </summary> + public static RelativeHumidity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static RelativeHumidity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RelativeHumidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RelativeHumidityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => RelativeHumidity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RelativeHumidityUnit.Percent"/> + /// </summary> + public double Percent => As(RelativeHumidityUnit.Percent); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RelativeHumidityUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<RelativeHumidity>(RelativeHumidityUnit.Percent, RelativeHumidityUnit.Percent, quantity => quantity); + + // Register in unit converter: BaseUnit -> RelativeHumidityUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RelativeHumidityUnit.Percent, new CultureInfo("en-US"), false, true, new string[]{"%RH"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RelativeHumidityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RelativeHumidityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="RelativeHumidity"/> from <see cref="RelativeHumidityUnit.Percent"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RelativeHumidity FromPercent(QuantityValue percent) + { + double value = (double) percent; + return new RelativeHumidity(value, RelativeHumidityUnit.Percent); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RelativeHumidityUnit" /> to <see cref="RelativeHumidity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>RelativeHumidity unit value.</returns> + public static RelativeHumidity From(QuantityValue value, RelativeHumidityUnit fromUnit) + { + return new RelativeHumidity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static RelativeHumidity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static RelativeHumidity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<RelativeHumidity, RelativeHumidityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out RelativeHumidity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out RelativeHumidity result) + { + return QuantityParser.Default.TryParse<RelativeHumidity, RelativeHumidityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RelativeHumidityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RelativeHumidityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RelativeHumidityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RelativeHumidityUnit)"/> + public static bool TryParseUnit(string str, out RelativeHumidityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RelativeHumidityUnit unit) + { + return UnitParser.Default.TryParse<RelativeHumidityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static RelativeHumidity operator -(RelativeHumidity right) + { + return new RelativeHumidity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="RelativeHumidity"/> from adding two <see cref="RelativeHumidity"/>.</summary> + public static RelativeHumidity operator +(RelativeHumidity left, RelativeHumidity right) + { + return new RelativeHumidity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RelativeHumidity"/> from subtracting two <see cref="RelativeHumidity"/>.</summary> + public static RelativeHumidity operator -(RelativeHumidity left, RelativeHumidity right) + { + return new RelativeHumidity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RelativeHumidity"/> from multiplying value and <see cref="RelativeHumidity"/>.</summary> + public static RelativeHumidity operator *(double left, RelativeHumidity right) + { + return new RelativeHumidity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="RelativeHumidity"/> from multiplying value and <see cref="RelativeHumidity"/>.</summary> + public static RelativeHumidity operator *(RelativeHumidity left, double right) + { + return new RelativeHumidity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="RelativeHumidity"/> from dividing <see cref="RelativeHumidity"/> by value.</summary> + public static RelativeHumidity operator /(RelativeHumidity left, double right) + { + return new RelativeHumidity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="RelativeHumidity"/> by <see cref="RelativeHumidity"/>.</summary> + public static double operator /(RelativeHumidity left, RelativeHumidity right) + { + return left.Percent / right.Percent; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(RelativeHumidity left, RelativeHumidity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(RelativeHumidity left, RelativeHumidity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(RelativeHumidity left, RelativeHumidity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(RelativeHumidity left, RelativeHumidity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="RelativeHumidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RelativeHumidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(RelativeHumidity left, RelativeHumidity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="RelativeHumidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RelativeHumidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(RelativeHumidity left, RelativeHumidity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RelativeHumidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RelativeHumidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is RelativeHumidity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RelativeHumidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RelativeHumidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(RelativeHumidity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="RelativeHumidity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is RelativeHumidity otherQuantity)) throw new ArgumentException("Expected type RelativeHumidity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="RelativeHumidity"/> with another <see cref="RelativeHumidity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(RelativeHumidity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another RelativeHumidity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(RelativeHumidity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current RelativeHumidity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RelativeHumidityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RelativeHumidityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this RelativeHumidity to another RelativeHumidity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A RelativeHumidity with the specified unit.</returns> + public RelativeHumidity ToUnit(RelativeHumidityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="RelativeHumidity"/> to another <see cref="RelativeHumidity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A RelativeHumidity with the specified unit.</returns> + public RelativeHumidity ToUnit(RelativeHumidityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(RelativeHumidity), Unit, typeof(RelativeHumidity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (RelativeHumidity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="RelativeHumidity"/> to another <see cref="RelativeHumidity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="RelativeHumidity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RelativeHumidityUnit unit, [NotNullWhen(true)] out RelativeHumidity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + RelativeHumidity? convertedOrNull = (Unit, unit) switch + { + // RelativeHumidityUnit -> BaseUnit + + // BaseUnit -> RelativeHumidityUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RelativeHumidityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RelativeHumidityUnit> IQuantity<RelativeHumidityUnit>.ToUnit(RelativeHumidityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RelativeHumidityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(RelativeHumidity)) + return this; + else if (conversionType == typeof(RelativeHumidityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return RelativeHumidity.Info; + else if (conversionType == typeof(BaseDimensions)) + return RelativeHumidity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidityUnit.g.cs new file mode 100644 index 0000000000..5962021a21 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RelativeHumidity/RelativeHumidityUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RelativeHumidityUnit + { + Percent = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAcceleration.csproj b/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAcceleration.csproj new file mode 100644 index 0000000000..a1d44e8c7d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAcceleration.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET RotationalAcceleration</Title> + <Description>Adds RotationalAcceleration units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>rotationalacceleration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{e2110137-6a36-f4d1-2219-26eb18fee74d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.RotationalAcceleration</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAcceleration.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAcceleration.g.cs new file mode 100644 index 0000000000..28c46624e3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAcceleration.g.cs @@ -0,0 +1,901 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Angular acceleration is the rate of change of rotational speed. + /// </summary> + [DataContract] + public readonly partial struct RotationalAcceleration : IArithmeticQuantity<RotationalAcceleration, RotationalAccelerationUnit, double>, IEquatable<RotationalAcceleration>, IComparable, IComparable<RotationalAcceleration>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RotationalAccelerationUnit? _unit; + + static RotationalAcceleration() + { + BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); + BaseUnit = RotationalAccelerationUnit.RadianPerSecondSquared; + Units = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast<RotationalAccelerationUnit>().ToArray(); + Zero = new RotationalAcceleration(0, BaseUnit); + Info = new QuantityInfo<RotationalAccelerationUnit>("RotationalAcceleration", + new UnitInfo<RotationalAccelerationUnit>[] + { + new UnitInfo<RotationalAccelerationUnit>(RotationalAccelerationUnit.DegreePerSecondSquared, "DegreesPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<RotationalAccelerationUnit>(RotationalAccelerationUnit.RadianPerSecondSquared, "RadiansPerSecondSquared", BaseUnits.Undefined), + new UnitInfo<RotationalAccelerationUnit>(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, "RevolutionsPerMinutePerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalAccelerationUnit>(RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionsPerSecondSquared", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public RotationalAcceleration(double value, RotationalAccelerationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="RotationalAcceleration" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RotationalAccelerationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. + /// </summary> + public static RotationalAccelerationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the RotationalAcceleration quantity. + /// </summary> + public static RotationalAccelerationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. + /// </summary> + public static RotationalAcceleration Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static RotationalAcceleration AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RotationalAccelerationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalAccelerationUnit.DegreePerSecondSquared"/> + /// </summary> + public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalAccelerationUnit.RadianPerSecondSquared"/> + /// </summary> + public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalAccelerationUnit.RevolutionPerMinutePerSecond"/> + /// </summary> + public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalAccelerationUnit.RevolutionPerSecondSquared"/> + /// </summary> + public double RevolutionsPerSecondSquared => As(RotationalAccelerationUnit.RevolutionPerSecondSquared); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RotationalAccelerationUnit -> BaseUnit + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.DegreePerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared)); + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared)); + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.RevolutionPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity); + + // Register in unit converter: BaseUnit -> RotationalAccelerationUnit + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.DegreePerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.DegreePerSecondSquared)); + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerMinutePerSecond, quantity => quantity.ToUnit(RotationalAccelerationUnit.RevolutionPerMinutePerSecond)); + unitConverter.SetConversionFunction<RotationalAcceleration>(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RevolutionPerSecondSquared)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalAccelerationUnit.DegreePerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"°/s²", "deg/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalAccelerationUnit.RadianPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"rad/s²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, new CultureInfo("en-US"), false, true, new string[]{"rpm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalAccelerationUnit.RevolutionPerSecondSquared, new CultureInfo("en-US"), false, true, new string[]{"r/s²"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RotationalAccelerationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RotationalAccelerationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="RotationalAcceleration"/> from <see cref="RotationalAccelerationUnit.DegreePerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) + { + double value = (double) degreespersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="RotationalAcceleration"/> from <see cref="RotationalAccelerationUnit.RadianPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) + { + double value = (double) radianspersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); + } + + /// <summary> + /// Creates a <see cref="RotationalAcceleration"/> from <see cref="RotationalAccelerationUnit.RevolutionPerMinutePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) + { + double value = (double) revolutionsperminutepersecond; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalAcceleration"/> from <see cref="RotationalAccelerationUnit.RevolutionPerSecondSquared"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalAcceleration FromRevolutionsPerSecondSquared(QuantityValue revolutionspersecondsquared) + { + double value = (double) revolutionspersecondsquared; + return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerSecondSquared); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RotationalAccelerationUnit" /> to <see cref="RotationalAcceleration" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>RotationalAcceleration unit value.</returns> + public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) + { + return new RotationalAcceleration((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static RotationalAcceleration Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static RotationalAcceleration Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<RotationalAcceleration, RotationalAccelerationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out RotationalAcceleration result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out RotationalAcceleration result) + { + return QuantityParser.Default.TryParse<RotationalAcceleration, RotationalAccelerationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalAccelerationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RotationalAccelerationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RotationalAccelerationUnit)"/> + public static bool TryParseUnit(string str, out RotationalAccelerationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalAccelerationUnit unit) + { + return UnitParser.Default.TryParse<RotationalAccelerationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static RotationalAcceleration operator -(RotationalAcceleration right) + { + return new RotationalAcceleration(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalAcceleration"/> from adding two <see cref="RotationalAcceleration"/>.</summary> + public static RotationalAcceleration operator +(RotationalAcceleration left, RotationalAcceleration right) + { + return new RotationalAcceleration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalAcceleration"/> from subtracting two <see cref="RotationalAcceleration"/>.</summary> + public static RotationalAcceleration operator -(RotationalAcceleration left, RotationalAcceleration right) + { + return new RotationalAcceleration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalAcceleration"/> from multiplying value and <see cref="RotationalAcceleration"/>.</summary> + public static RotationalAcceleration operator *(double left, RotationalAcceleration right) + { + return new RotationalAcceleration(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalAcceleration"/> from multiplying value and <see cref="RotationalAcceleration"/>.</summary> + public static RotationalAcceleration operator *(RotationalAcceleration left, double right) + { + return new RotationalAcceleration(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="RotationalAcceleration"/> from dividing <see cref="RotationalAcceleration"/> by value.</summary> + public static RotationalAcceleration operator /(RotationalAcceleration left, double right) + { + return new RotationalAcceleration(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="RotationalAcceleration"/> by <see cref="RotationalAcceleration"/>.</summary> + public static double operator /(RotationalAcceleration left, RotationalAcceleration right) + { + return left.RadiansPerSecondSquared / right.RadiansPerSecondSquared; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="RotationalAcceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalAcceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="RotationalAcceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalAcceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalAcceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalAcceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is RotationalAcceleration otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalAcceleration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalAcceleration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(RotationalAcceleration other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="RotationalAcceleration"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is RotationalAcceleration otherQuantity)) throw new ArgumentException("Expected type RotationalAcceleration.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="RotationalAcceleration"/> with another <see cref="RotationalAcceleration"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(RotationalAcceleration other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another RotationalAcceleration within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current RotationalAcceleration.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RotationalAccelerationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RotationalAccelerationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A RotationalAcceleration with the specified unit.</returns> + public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="RotationalAcceleration"/> to another <see cref="RotationalAcceleration"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A RotationalAcceleration with the specified unit.</returns> + public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(RotationalAcceleration), Unit, typeof(RotationalAcceleration), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (RotationalAcceleration)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="RotationalAcceleration"/> to another <see cref="RotationalAcceleration"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="RotationalAcceleration"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RotationalAccelerationUnit unit, [NotNullWhen(true)] out RotationalAcceleration? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + RotationalAcceleration? convertedOrNull = (Unit, unit) switch + { + // RotationalAccelerationUnit -> BaseUnit + (RotationalAccelerationUnit.DegreePerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared) => new RotationalAcceleration((Math.PI / 180) * _value, RotationalAccelerationUnit.RadianPerSecondSquared), + (RotationalAccelerationUnit.RevolutionPerMinutePerSecond, RotationalAccelerationUnit.RadianPerSecondSquared) => new RotationalAcceleration(((2 * Math.PI) / 60) * _value, RotationalAccelerationUnit.RadianPerSecondSquared), + (RotationalAccelerationUnit.RevolutionPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared) => new RotationalAcceleration((2 * Math.PI) * _value, RotationalAccelerationUnit.RadianPerSecondSquared), + + // BaseUnit -> RotationalAccelerationUnit + (RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.DegreePerSecondSquared) => new RotationalAcceleration((180 / Math.PI) * _value, RotationalAccelerationUnit.DegreePerSecondSquared), + (RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerMinutePerSecond) => new RotationalAcceleration((60 / (2 * Math.PI)) * _value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond), + (RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerSecondSquared) => new RotationalAcceleration((1 / (2 * Math.PI)) * _value, RotationalAccelerationUnit.RevolutionPerSecondSquared), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RotationalAccelerationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RotationalAccelerationUnit> IQuantity<RotationalAccelerationUnit>.ToUnit(RotationalAccelerationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RotationalAccelerationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(RotationalAcceleration)) + return this; + else if (conversionType == typeof(RotationalAccelerationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return RotationalAcceleration.Info; + else if (conversionType == typeof(BaseDimensions)) + return RotationalAcceleration.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAccelerationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAccelerationUnit.g.cs new file mode 100644 index 0000000000..78d18c4ea1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalAcceleration/RotationalAccelerationUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RotationalAccelerationUnit + { + DegreePerSecondSquared = 1, + RadianPerSecondSquared = 2, + RevolutionPerMinutePerSecond = 3, + RevolutionPerSecondSquared = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeed.csproj b/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeed.csproj new file mode 100644 index 0000000000..bf2f6a68ea --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeed.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET RotationalSpeed</Title> + <Description>Adds RotationalSpeed units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>rotationalspeed unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{934ef064-2dce-6d50-64e9-d4d2c4d41a81}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.RotationalSpeed</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeed.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeed.g.cs new file mode 100644 index 0000000000..31c158cf65 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeed.g.cs @@ -0,0 +1,1102 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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"). + /// </summary> + [DataContract] + public readonly partial struct RotationalSpeed : IArithmeticQuantity<RotationalSpeed, RotationalSpeedUnit, double>, IEquatable<RotationalSpeed>, IComparable, IComparable<RotationalSpeed>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RotationalSpeedUnit? _unit; + + static RotationalSpeed() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + BaseUnit = RotationalSpeedUnit.RadianPerSecond; + Units = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast<RotationalSpeedUnit>().ToArray(); + Zero = new RotationalSpeed(0, BaseUnit); + Info = new QuantityInfo<RotationalSpeedUnit>("RotationalSpeed", + new UnitInfo<RotationalSpeedUnit>[] + { + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.CentiradianPerSecond, "CentiradiansPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.DeciradianPerSecond, "DeciradiansPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.DegreePerMinute, "DegreesPerMinute", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.DegreePerSecond, "DegreesPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.MicrodegreePerSecond, "MicrodegreesPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.MicroradianPerSecond, "MicroradiansPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.MillidegreePerSecond, "MillidegreesPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.MilliradianPerSecond, "MilliradiansPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.NanodegreePerSecond, "NanodegreesPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.NanoradianPerSecond, "NanoradiansPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.RadianPerSecond, "RadiansPerSecond", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.RevolutionPerMinute, "RevolutionsPerMinute", BaseUnits.Undefined), + new UnitInfo<RotationalSpeedUnit>(RotationalSpeedUnit.RevolutionPerSecond, "RevolutionsPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public RotationalSpeed(double value, RotationalSpeedUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="RotationalSpeed" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RotationalSpeedUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. + /// </summary> + public static RotationalSpeedUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the RotationalSpeed quantity. + /// </summary> + public static RotationalSpeedUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. + /// </summary> + public static RotationalSpeed Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static RotationalSpeed AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RotationalSpeedUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.CentiradianPerSecond"/> + /// </summary> + public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.DeciradianPerSecond"/> + /// </summary> + public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.DegreePerMinute"/> + /// </summary> + public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.DegreePerSecond"/> + /// </summary> + public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.MicrodegreePerSecond"/> + /// </summary> + public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.MicroradianPerSecond"/> + /// </summary> + public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.MillidegreePerSecond"/> + /// </summary> + public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.MilliradianPerSecond"/> + /// </summary> + public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.NanodegreePerSecond"/> + /// </summary> + public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.NanoradianPerSecond"/> + /// </summary> + public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.RadianPerSecond"/> + /// </summary> + public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.RevolutionPerMinute"/> + /// </summary> + public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalSpeedUnit.RevolutionPerSecond"/> + /// </summary> + public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RotationalSpeedUnit -> BaseUnit + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.CentiradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.DeciradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.DegreePerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.DegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.MillidegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.MilliradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.NanodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.NanoradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RevolutionPerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RevolutionPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> RotationalSpeedUnit + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.CentiradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.CentiradianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DeciradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.DeciradianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerMinute, quantity => quantity.ToUnit(RotationalSpeedUnit.DegreePerMinute)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.DegreePerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicrodegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MicrodegreePerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicroradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MicroradianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MillidegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MillidegreePerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MilliradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MilliradianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanodegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.NanodegreePerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanoradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.NanoradianPerSecond)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerMinute, quantity => quantity.ToUnit(RotationalSpeedUnit.RevolutionPerMinute)); + unitConverter.SetConversionFunction<RotationalSpeed>(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RevolutionPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.CentiradianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"crad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.CentiradianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"срад/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.DeciradianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"drad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.DeciradianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"драд/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.DegreePerMinute, new CultureInfo("en-US"), false, true, new string[]{"°/min", "deg/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.DegreePerSecond, new CultureInfo("en-US"), false, true, new string[]{"°/s", "deg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.DegreePerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"°/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MicrodegreePerSecond, new CultureInfo("en-US"), false, true, new string[]{"µ°/s", "µdeg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MicrodegreePerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мк°/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MicroradianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µrad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MicroradianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мкрад/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MillidegreePerSecond, new CultureInfo("en-US"), false, true, new string[]{"m°/s", "mdeg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MillidegreePerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"м°/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MilliradianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mrad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.MilliradianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мрад/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.NanodegreePerSecond, new CultureInfo("en-US"), false, true, new string[]{"n°/s", "ndeg/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.NanodegreePerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"н°/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.NanoradianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"nrad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.NanoradianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"нрад/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.RadianPerSecond, new CultureInfo("en-US"), false, true, new string[]{"rad/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.RadianPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"рад/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.RevolutionPerMinute, new CultureInfo("en-US"), false, true, new string[]{"rpm", "r/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.RevolutionPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"об/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.RevolutionPerSecond, new CultureInfo("en-US"), false, true, new string[]{"r/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalSpeedUnit.RevolutionPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"об/с"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RotationalSpeedUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RotationalSpeedUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.CentiradianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) + { + double value = (double) centiradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.DeciradianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) + { + double value = (double) deciradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.DegreePerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) + { + double value = (double) degreesperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.DegreePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) + { + double value = (double) degreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.MicrodegreePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) + { + double value = (double) microdegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.MicroradianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) + { + double value = (double) microradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.MillidegreePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) + { + double value = (double) millidegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.MilliradianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) + { + double value = (double) milliradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.NanodegreePerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) + { + double value = (double) nanodegreespersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.NanoradianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) + { + double value = (double) nanoradianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.RadianPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) + { + double value = (double) radianspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.RevolutionPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) + { + double value = (double) revolutionsperminute; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); + } + + /// <summary> + /// Creates a <see cref="RotationalSpeed"/> from <see cref="RotationalSpeedUnit.RevolutionPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) + { + double value = (double) revolutionspersecond; + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RotationalSpeedUnit" /> to <see cref="RotationalSpeed" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>RotationalSpeed unit value.</returns> + public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) + { + return new RotationalSpeed((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static RotationalSpeed Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static RotationalSpeed Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<RotationalSpeed, RotationalSpeedUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out RotationalSpeed result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out RotationalSpeed result) + { + return QuantityParser.Default.TryParse<RotationalSpeed, RotationalSpeedUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalSpeedUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalSpeedUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RotationalSpeedUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RotationalSpeedUnit)"/> + public static bool TryParseUnit(string str, out RotationalSpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalSpeedUnit unit) + { + return UnitParser.Default.TryParse<RotationalSpeedUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static RotationalSpeed operator -(RotationalSpeed right) + { + return new RotationalSpeed(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalSpeed"/> from adding two <see cref="RotationalSpeed"/>.</summary> + public static RotationalSpeed operator +(RotationalSpeed left, RotationalSpeed right) + { + return new RotationalSpeed(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalSpeed"/> from subtracting two <see cref="RotationalSpeed"/>.</summary> + public static RotationalSpeed operator -(RotationalSpeed left, RotationalSpeed right) + { + return new RotationalSpeed(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalSpeed"/> from multiplying value and <see cref="RotationalSpeed"/>.</summary> + public static RotationalSpeed operator *(double left, RotationalSpeed right) + { + return new RotationalSpeed(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalSpeed"/> from multiplying value and <see cref="RotationalSpeed"/>.</summary> + public static RotationalSpeed operator *(RotationalSpeed left, double right) + { + return new RotationalSpeed(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="RotationalSpeed"/> from dividing <see cref="RotationalSpeed"/> by value.</summary> + public static RotationalSpeed operator /(RotationalSpeed left, double right) + { + return new RotationalSpeed(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="RotationalSpeed"/> by <see cref="RotationalSpeed"/>.</summary> + public static double operator /(RotationalSpeed left, RotationalSpeed right) + { + return left.RadiansPerSecond / right.RadiansPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(RotationalSpeed left, RotationalSpeed right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(RotationalSpeed left, RotationalSpeed right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(RotationalSpeed left, RotationalSpeed right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(RotationalSpeed left, RotationalSpeed right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="RotationalSpeed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalSpeed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(RotationalSpeed left, RotationalSpeed right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="RotationalSpeed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalSpeed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(RotationalSpeed left, RotationalSpeed right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalSpeed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalSpeed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is RotationalSpeed otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalSpeed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalSpeed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(RotationalSpeed other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="RotationalSpeed"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is RotationalSpeed otherQuantity)) throw new ArgumentException("Expected type RotationalSpeed.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="RotationalSpeed"/> with another <see cref="RotationalSpeed"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(RotationalSpeed other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another RotationalSpeed within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current RotationalSpeed.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RotationalSpeedUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RotationalSpeedUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A RotationalSpeed with the specified unit.</returns> + public RotationalSpeed ToUnit(RotationalSpeedUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="RotationalSpeed"/> to another <see cref="RotationalSpeed"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A RotationalSpeed with the specified unit.</returns> + public RotationalSpeed ToUnit(RotationalSpeedUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(RotationalSpeed), Unit, typeof(RotationalSpeed), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (RotationalSpeed)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="RotationalSpeed"/> to another <see cref="RotationalSpeed"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="RotationalSpeed"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RotationalSpeedUnit unit, [NotNullWhen(true)] out RotationalSpeed? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + RotationalSpeed? convertedOrNull = (Unit, unit) switch + { + // RotationalSpeedUnit -> BaseUnit + (RotationalSpeedUnit.CentiradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-2d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.DeciradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-1d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.DegreePerMinute, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((Math.PI / (180 * 60)) * _value, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.DegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((Math.PI / 180) * _value, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(((Math.PI / 180) * _value) * 1e-6d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-6d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.MillidegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(((Math.PI / 180) * _value) * 1e-3d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.MilliradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-3d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.NanodegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(((Math.PI / 180) * _value) * 1e-9d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.NanoradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-9d, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.RevolutionPerMinute, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value * 6.2831853072) / 60, RotationalSpeedUnit.RadianPerSecond), + (RotationalSpeedUnit.RevolutionPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(_value * 6.2831853072, RotationalSpeedUnit.RadianPerSecond), + + // BaseUnit -> RotationalSpeedUnit + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.CentiradianPerSecond) => new RotationalSpeed((_value) / 1e-2d, RotationalSpeedUnit.CentiradianPerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DeciradianPerSecond) => new RotationalSpeed((_value) / 1e-1d, RotationalSpeedUnit.DeciradianPerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerMinute) => new RotationalSpeed((180 * 60 / Math.PI) * _value, RotationalSpeedUnit.DegreePerMinute), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerSecond) => new RotationalSpeed((180 / Math.PI) * _value, RotationalSpeedUnit.DegreePerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicrodegreePerSecond) => new RotationalSpeed(((180 / Math.PI) * _value) / 1e-6d, RotationalSpeedUnit.MicrodegreePerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicroradianPerSecond) => new RotationalSpeed((_value) / 1e-6d, RotationalSpeedUnit.MicroradianPerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MillidegreePerSecond) => new RotationalSpeed(((180 / Math.PI) * _value) / 1e-3d, RotationalSpeedUnit.MillidegreePerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MilliradianPerSecond) => new RotationalSpeed((_value) / 1e-3d, RotationalSpeedUnit.MilliradianPerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanodegreePerSecond) => new RotationalSpeed(((180 / Math.PI) * _value) / 1e-9d, RotationalSpeedUnit.NanodegreePerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanoradianPerSecond) => new RotationalSpeed((_value) / 1e-9d, RotationalSpeedUnit.NanoradianPerSecond), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerMinute) => new RotationalSpeed((_value / 6.2831853072) * 60, RotationalSpeedUnit.RevolutionPerMinute), + (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerSecond) => new RotationalSpeed(_value / 6.2831853072, RotationalSpeedUnit.RevolutionPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RotationalSpeedUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RotationalSpeedUnit> IQuantity<RotationalSpeedUnit>.ToUnit(RotationalSpeedUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RotationalSpeedUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(RotationalSpeed)) + return this; + else if (conversionType == typeof(RotationalSpeedUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return RotationalSpeed.Info; + else if (conversionType == typeof(BaseDimensions)) + return RotationalSpeed.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeedUnit.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeedUnit.g.cs new file mode 100644 index 0000000000..c764514ede --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalSpeed/RotationalSpeedUnit.g.cs @@ -0,0 +1,44 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RotationalSpeedUnit + { + CentiradianPerSecond = 1, + DeciradianPerSecond = 2, + DegreePerMinute = 3, + DegreePerSecond = 4, + MicrodegreePerSecond = 5, + MicroradianPerSecond = 6, + MillidegreePerSecond = 7, + MilliradianPerSecond = 8, + NanodegreePerSecond = 9, + NanoradianPerSecond = 10, + RadianPerSecond = 11, + RevolutionPerMinute = 12, + RevolutionPerSecond = 13, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffness.csproj b/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffness.csproj new file mode 100644 index 0000000000..d569ddc6b3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffness.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET RotationalStiffness</Title> + <Description>Adds RotationalStiffness units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>rotationalstiffness unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{3788f245-ea6d-eb5d-80de-f25ab30a51cc}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.RotationalStiffness</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffness.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffness.g.cs new file mode 100644 index 0000000000..2b8e430643 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffness.g.cs @@ -0,0 +1,1510 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness + /// </summary> + [DataContract] + public readonly partial struct RotationalStiffness : IArithmeticQuantity<RotationalStiffness, RotationalStiffnessUnit, double>, IEquatable<RotationalStiffness>, IComparable, IComparable<RotationalStiffness>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RotationalStiffnessUnit? _unit; + + static RotationalStiffness() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + BaseUnit = RotationalStiffnessUnit.NewtonMeterPerRadian; + Units = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast<RotationalStiffnessUnit>().ToArray(); + Zero = new RotationalStiffness(0, BaseUnit); + Info = new QuantityInfo<RotationalStiffnessUnit>("RotationalStiffness", + new UnitInfo<RotationalStiffnessUnit>[] + { + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.CentinewtonMeterPerDegree, "CentinewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, "CentinewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, "CentinewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.DecanewtonMeterPerDegree, "DecanewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, "DecanewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, "DecanewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.DecinewtonMeterPerDegree, "DecinewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, "DecinewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, "DecinewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.KilonewtonMeterPerDegree, "KilonewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.KilonewtonMeterPerRadian, "KilonewtonMetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, "KilonewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, "KilonewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, "KilopoundForceFeetPerDegrees", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MeganewtonMeterPerDegree, "MeganewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MeganewtonMeterPerRadian, "MeganewtonMetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, "MeganewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, "MeganewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MicronewtonMeterPerDegree, "MicronewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, "MicronewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, "MicronewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MillinewtonMeterPerDegree, "MillinewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, "MillinewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, "MillinewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NanonewtonMeterPerDegree, "NanonewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, "NanonewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, "NanonewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NewtonMeterPerDegree, "NewtonMetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NewtonMeterPerRadian, "NewtonMetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NewtonMillimeterPerDegree, "NewtonMillimetersPerDegree", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.NewtonMillimeterPerRadian, "NewtonMillimetersPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.PoundForceFeetPerRadian, "PoundForceFeetPerRadian", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessUnit>(RotationalStiffnessUnit.PoundForceFootPerDegrees, "PoundForceFeetPerDegrees", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public RotationalStiffness(double value, RotationalStiffnessUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="RotationalStiffness" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RotationalStiffnessUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. + /// </summary> + public static RotationalStiffnessUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the RotationalStiffness quantity. + /// </summary> + public static RotationalStiffnessUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. + /// </summary> + public static RotationalStiffness Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static RotationalStiffness AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RotationalStiffnessUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.CentinewtonMeterPerDegree"/> + /// </summary> + public double CentinewtonMetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.CentinewtonMillimeterPerDegree"/> + /// </summary> + public double CentinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.CentinewtonMillimeterPerRadian"/> + /// </summary> + public double CentinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.DecanewtonMeterPerDegree"/> + /// </summary> + public double DecanewtonMetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.DecanewtonMillimeterPerDegree"/> + /// </summary> + public double DecanewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.DecanewtonMillimeterPerRadian"/> + /// </summary> + public double DecanewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.DecinewtonMeterPerDegree"/> + /// </summary> + public double DecinewtonMetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.DecinewtonMillimeterPerDegree"/> + /// </summary> + public double DecinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.DecinewtonMillimeterPerRadian"/> + /// </summary> + public double DecinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.KilonewtonMeterPerDegree"/> + /// </summary> + public double KilonewtonMetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.KilonewtonMeterPerRadian"/> + /// </summary> + public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.KilonewtonMillimeterPerDegree"/> + /// </summary> + public double KilonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.KilonewtonMillimeterPerRadian"/> + /// </summary> + public double KilonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.KilopoundForceFootPerDegrees"/> + /// </summary> + public double KilopoundForceFeetPerDegrees => As(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MeganewtonMeterPerDegree"/> + /// </summary> + public double MeganewtonMetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MeganewtonMeterPerRadian"/> + /// </summary> + public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MeganewtonMillimeterPerDegree"/> + /// </summary> + public double MeganewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MeganewtonMillimeterPerRadian"/> + /// </summary> + public double MeganewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MicronewtonMeterPerDegree"/> + /// </summary> + public double MicronewtonMetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MicronewtonMillimeterPerDegree"/> + /// </summary> + public double MicronewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MicronewtonMillimeterPerRadian"/> + /// </summary> + public double MicronewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MillinewtonMeterPerDegree"/> + /// </summary> + public double MillinewtonMetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MillinewtonMillimeterPerDegree"/> + /// </summary> + public double MillinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.MillinewtonMillimeterPerRadian"/> + /// </summary> + public double MillinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NanonewtonMeterPerDegree"/> + /// </summary> + public double NanonewtonMetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NanonewtonMillimeterPerDegree"/> + /// </summary> + public double NanonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NanonewtonMillimeterPerRadian"/> + /// </summary> + public double NanonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NewtonMeterPerDegree"/> + /// </summary> + public double NewtonMetersPerDegree => As(RotationalStiffnessUnit.NewtonMeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NewtonMeterPerRadian"/> + /// </summary> + public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NewtonMillimeterPerDegree"/> + /// </summary> + public double NewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NewtonMillimeterPerDegree); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.NewtonMillimeterPerRadian"/> + /// </summary> + public double NewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NewtonMillimeterPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.PoundForceFeetPerRadian"/> + /// </summary> + public double PoundForceFeetPerRadian => As(RotationalStiffnessUnit.PoundForceFeetPerRadian); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessUnit.PoundForceFootPerDegrees"/> + /// </summary> + public double PoundForceFeetPerDegrees => As(RotationalStiffnessUnit.PoundForceFootPerDegrees); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RotationalStiffnessUnit -> BaseUnit + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.CentinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.DecanewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.DecinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.KilonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.KilonewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MeganewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MeganewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MicronewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MillinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NanonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.PoundForceFeetPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.PoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity); + + // Register in unit converter: BaseUnit -> RotationalStiffnessUnit + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilopoundForceFootPerDegrees, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilopoundForceFootPerDegrees)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerDegree)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFeetPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.PoundForceFeetPerRadian)); + unitConverter.SetConversionFunction<RotationalStiffness>(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFootPerDegrees, quantity => quantity.ToUnit(RotationalStiffnessUnit.PoundForceFootPerDegrees)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.CentinewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"cN·m/deg", "cNm/deg", "cN·m/°", "cNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"cN·mm/deg", "cNmm/deg", "cN·mm/°", "cNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"cN·mm/rad", "cNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.DecanewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"daN·m/deg", "daNm/deg", "daN·m/°", "daNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"daN·mm/deg", "daNmm/deg", "daN·mm/°", "daNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"daN·mm/rad", "daNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.DecinewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"dN·m/deg", "dNm/deg", "dN·m/°", "dNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"dN·mm/deg", "dNmm/deg", "dN·mm/°", "dNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"dN·mm/rad", "dNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.KilonewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"kN·m/deg", "kNm/deg", "kN·m/°", "kNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.KilonewtonMeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"kN·m/rad", "kNm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"kN·mm/deg", "kNmm/deg", "kN·mm/°", "kNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"kN·mm/rad", "kNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, new CultureInfo("en-US"), false, true, new string[]{"kipf·ft/°", "kip·ft/°g", "k·ft/°", "kipf·ft/deg", "kip·ft/deg", "k·ft/deg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MeganewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"MN·m/deg", "MNm/deg", "MN·m/°", "MNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MeganewtonMeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"MN·m/rad", "MNm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"MN·mm/deg", "MNmm/deg", "MN·mm/°", "MNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"MN·mm/rad", "MNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MicronewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"µN·m/deg", "µNm/deg", "µN·m/°", "µNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"µN·mm/deg", "µNmm/deg", "µN·mm/°", "µNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"µN·mm/rad", "µNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MillinewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"mN·m/deg", "mNm/deg", "mN·m/°", "mNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"mN·mm/deg", "mNmm/deg", "mN·mm/°", "mNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"mN·mm/rad", "mNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NanonewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"nN·m/deg", "nNm/deg", "nN·m/°", "nNm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"nN·mm/deg", "nNmm/deg", "nN·mm/°", "nNmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"nN·mm/rad", "nNmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NewtonMeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"N·m/deg", "Nm/deg", "N·m/°", "Nm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NewtonMeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"N·m/rad", "Nm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NewtonMillimeterPerDegree, new CultureInfo("en-US"), false, true, new string[]{"N·mm/deg", "Nmm/deg", "N·mm/°", "Nmm/°"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.NewtonMillimeterPerRadian, new CultureInfo("en-US"), false, true, new string[]{"N·mm/rad", "Nmm/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.PoundForceFeetPerRadian, new CultureInfo("en-US"), false, true, new string[]{"lbf·ft/rad"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessUnit.PoundForceFootPerDegrees, new CultureInfo("en-US"), false, true, new string[]{"lbf·ft/deg"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RotationalStiffnessUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RotationalStiffnessUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.CentinewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromCentinewtonMetersPerDegree(QuantityValue centinewtonmetersperdegree) + { + double value = (double) centinewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.CentinewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromCentinewtonMillimetersPerDegree(QuantityValue centinewtonmillimetersperdegree) + { + double value = (double) centinewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.CentinewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromCentinewtonMillimetersPerRadian(QuantityValue centinewtonmillimetersperradian) + { + double value = (double) centinewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.DecanewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromDecanewtonMetersPerDegree(QuantityValue decanewtonmetersperdegree) + { + double value = (double) decanewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.DecanewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromDecanewtonMillimetersPerDegree(QuantityValue decanewtonmillimetersperdegree) + { + double value = (double) decanewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.DecanewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromDecanewtonMillimetersPerRadian(QuantityValue decanewtonmillimetersperradian) + { + double value = (double) decanewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.DecinewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromDecinewtonMetersPerDegree(QuantityValue decinewtonmetersperdegree) + { + double value = (double) decinewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.DecinewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromDecinewtonMillimetersPerDegree(QuantityValue decinewtonmillimetersperdegree) + { + double value = (double) decinewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.DecinewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromDecinewtonMillimetersPerRadian(QuantityValue decinewtonmillimetersperradian) + { + double value = (double) decinewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.KilonewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromKilonewtonMetersPerDegree(QuantityValue kilonewtonmetersperdegree) + { + double value = (double) kilonewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.KilonewtonMeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue kilonewtonmetersperradian) + { + double value = (double) kilonewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.KilonewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromKilonewtonMillimetersPerDegree(QuantityValue kilonewtonmillimetersperdegree) + { + double value = (double) kilonewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.KilonewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromKilonewtonMillimetersPerRadian(QuantityValue kilonewtonmillimetersperradian) + { + double value = (double) kilonewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.KilopoundForceFootPerDegrees"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromKilopoundForceFeetPerDegrees(QuantityValue kilopoundforcefeetperdegrees) + { + double value = (double) kilopoundforcefeetperdegrees; + return new RotationalStiffness(value, RotationalStiffnessUnit.KilopoundForceFootPerDegrees); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MeganewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMeganewtonMetersPerDegree(QuantityValue meganewtonmetersperdegree) + { + double value = (double) meganewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MeganewtonMeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue meganewtonmetersperradian) + { + double value = (double) meganewtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MeganewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMeganewtonMillimetersPerDegree(QuantityValue meganewtonmillimetersperdegree) + { + double value = (double) meganewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MeganewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMeganewtonMillimetersPerRadian(QuantityValue meganewtonmillimetersperradian) + { + double value = (double) meganewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MicronewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMicronewtonMetersPerDegree(QuantityValue micronewtonmetersperdegree) + { + double value = (double) micronewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MicronewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMicronewtonMillimetersPerDegree(QuantityValue micronewtonmillimetersperdegree) + { + double value = (double) micronewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MicronewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMicronewtonMillimetersPerRadian(QuantityValue micronewtonmillimetersperradian) + { + double value = (double) micronewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MillinewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMillinewtonMetersPerDegree(QuantityValue millinewtonmetersperdegree) + { + double value = (double) millinewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MillinewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMillinewtonMillimetersPerDegree(QuantityValue millinewtonmillimetersperdegree) + { + double value = (double) millinewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.MillinewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromMillinewtonMillimetersPerRadian(QuantityValue millinewtonmillimetersperradian) + { + double value = (double) millinewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NanonewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNanonewtonMetersPerDegree(QuantityValue nanonewtonmetersperdegree) + { + double value = (double) nanonewtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NanonewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNanonewtonMillimetersPerDegree(QuantityValue nanonewtonmillimetersperdegree) + { + double value = (double) nanonewtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NanonewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNanonewtonMillimetersPerRadian(QuantityValue nanonewtonmillimetersperradian) + { + double value = (double) nanonewtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NewtonMeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNewtonMetersPerDegree(QuantityValue newtonmetersperdegree) + { + double value = (double) newtonmetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NewtonMeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue newtonmetersperradian) + { + double value = (double) newtonmetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NewtonMillimeterPerDegree"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNewtonMillimetersPerDegree(QuantityValue newtonmillimetersperdegree) + { + double value = (double) newtonmillimetersperdegree; + return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerDegree); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.NewtonMillimeterPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromNewtonMillimetersPerRadian(QuantityValue newtonmillimetersperradian) + { + double value = (double) newtonmillimetersperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.PoundForceFeetPerRadian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromPoundForceFeetPerRadian(QuantityValue poundforcefeetperradian) + { + double value = (double) poundforcefeetperradian; + return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFeetPerRadian); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffness"/> from <see cref="RotationalStiffnessUnit.PoundForceFootPerDegrees"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffness FromPoundForceFeetPerDegrees(QuantityValue poundforcefeetperdegrees) + { + double value = (double) poundforcefeetperdegrees; + return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFootPerDegrees); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RotationalStiffnessUnit" /> to <see cref="RotationalStiffness" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>RotationalStiffness unit value.</returns> + public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) + { + return new RotationalStiffness((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static RotationalStiffness Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static RotationalStiffness Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<RotationalStiffness, RotationalStiffnessUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out RotationalStiffness result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out RotationalStiffness result) + { + return QuantityParser.Default.TryParse<RotationalStiffness, RotationalStiffnessUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalStiffnessUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalStiffnessUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RotationalStiffnessUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RotationalStiffnessUnit)"/> + public static bool TryParseUnit(string str, out RotationalStiffnessUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalStiffnessUnit unit) + { + return UnitParser.Default.TryParse<RotationalStiffnessUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static RotationalStiffness operator -(RotationalStiffness right) + { + return new RotationalStiffness(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalStiffness"/> from adding two <see cref="RotationalStiffness"/>.</summary> + public static RotationalStiffness operator +(RotationalStiffness left, RotationalStiffness right) + { + return new RotationalStiffness(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalStiffness"/> from subtracting two <see cref="RotationalStiffness"/>.</summary> + public static RotationalStiffness operator -(RotationalStiffness left, RotationalStiffness right) + { + return new RotationalStiffness(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalStiffness"/> from multiplying value and <see cref="RotationalStiffness"/>.</summary> + public static RotationalStiffness operator *(double left, RotationalStiffness right) + { + return new RotationalStiffness(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalStiffness"/> from multiplying value and <see cref="RotationalStiffness"/>.</summary> + public static RotationalStiffness operator *(RotationalStiffness left, double right) + { + return new RotationalStiffness(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="RotationalStiffness"/> from dividing <see cref="RotationalStiffness"/> by value.</summary> + public static RotationalStiffness operator /(RotationalStiffness left, double right) + { + return new RotationalStiffness(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="RotationalStiffness"/> by <see cref="RotationalStiffness"/>.</summary> + public static double operator /(RotationalStiffness left, RotationalStiffness right) + { + return left.NewtonMetersPerRadian / right.NewtonMetersPerRadian; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(RotationalStiffness left, RotationalStiffness right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(RotationalStiffness left, RotationalStiffness right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(RotationalStiffness left, RotationalStiffness right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(RotationalStiffness left, RotationalStiffness right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="RotationalStiffness"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffness, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(RotationalStiffness left, RotationalStiffness right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="RotationalStiffness"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffness, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(RotationalStiffness left, RotationalStiffness right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalStiffness"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffness, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is RotationalStiffness otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalStiffness"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffness, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(RotationalStiffness other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="RotationalStiffness"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is RotationalStiffness otherQuantity)) throw new ArgumentException("Expected type RotationalStiffness.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="RotationalStiffness"/> with another <see cref="RotationalStiffness"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(RotationalStiffness other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another RotationalStiffness within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current RotationalStiffness.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RotationalStiffnessUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RotationalStiffnessUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A RotationalStiffness with the specified unit.</returns> + public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="RotationalStiffness"/> to another <see cref="RotationalStiffness"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A RotationalStiffness with the specified unit.</returns> + public RotationalStiffness ToUnit(RotationalStiffnessUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(RotationalStiffness), Unit, typeof(RotationalStiffness), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (RotationalStiffness)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="RotationalStiffness"/> to another <see cref="RotationalStiffness"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="RotationalStiffness"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RotationalStiffnessUnit unit, [NotNullWhen(true)] out RotationalStiffness? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + RotationalStiffness? convertedOrNull = (Unit, unit) switch + { + // RotationalStiffnessUnit -> BaseUnit + (RotationalStiffnessUnit.CentinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.DecanewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.DecinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.KilonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.KilonewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.KilopoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 77682.6, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MeganewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MeganewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MicronewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MillinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.NanonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * (180 / Math.PI), RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.NewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 180 / Math.PI * 0.001, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.NewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 0.001, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.PoundForceFeetPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 1.3558179483314, RotationalStiffnessUnit.NewtonMeterPerRadian), + (RotationalStiffnessUnit.PoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 77.6826, RotationalStiffnessUnit.NewtonMeterPerRadian), + + // BaseUnit -> RotationalStiffnessUnit + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-2d, RotationalStiffnessUnit.CentinewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-2d, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-2d, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e1d, RotationalStiffnessUnit.DecanewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e1d, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e1d, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-1d, RotationalStiffnessUnit.DecinewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-1d, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-1d, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e3d, RotationalStiffnessUnit.KilonewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerRadian) => new RotationalStiffness((_value) / 1e3d, RotationalStiffnessUnit.KilonewtonMeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e3d, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e3d, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilopoundForceFootPerDegrees) => new RotationalStiffness(_value / 77682.6, RotationalStiffnessUnit.KilopoundForceFootPerDegrees), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e6d, RotationalStiffnessUnit.MeganewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerRadian) => new RotationalStiffness((_value) / 1e6d, RotationalStiffnessUnit.MeganewtonMeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e6d, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e6d, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-6d, RotationalStiffnessUnit.MicronewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-6d, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-6d, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-3d, RotationalStiffnessUnit.MillinewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-3d, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-3d, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-9d, RotationalStiffnessUnit.NanonewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-9d, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-9d, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerDegree) => new RotationalStiffness(_value / (180 / Math.PI), RotationalStiffnessUnit.NewtonMeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerDegree) => new RotationalStiffness(_value / 180 * Math.PI * 1000, RotationalStiffnessUnit.NewtonMillimeterPerDegree), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerRadian) => new RotationalStiffness(_value * 1000, RotationalStiffnessUnit.NewtonMillimeterPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFeetPerRadian) => new RotationalStiffness(_value / 1.3558179483314, RotationalStiffnessUnit.PoundForceFeetPerRadian), + (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFootPerDegrees) => new RotationalStiffness(_value / 77.6826, RotationalStiffnessUnit.PoundForceFootPerDegrees), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RotationalStiffnessUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RotationalStiffnessUnit> IQuantity<RotationalStiffnessUnit>.ToUnit(RotationalStiffnessUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RotationalStiffnessUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(RotationalStiffness)) + return this; + else if (conversionType == typeof(RotationalStiffnessUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return RotationalStiffness.Info; + else if (conversionType == typeof(BaseDimensions)) + return RotationalStiffness.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffnessUnit.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffnessUnit.g.cs new file mode 100644 index 0000000000..6905f8d976 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalStiffness/RotationalStiffnessUnit.g.cs @@ -0,0 +1,64 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RotationalStiffnessUnit + { + CentinewtonMeterPerDegree = 1, + CentinewtonMillimeterPerDegree = 2, + CentinewtonMillimeterPerRadian = 3, + DecanewtonMeterPerDegree = 4, + DecanewtonMillimeterPerDegree = 5, + DecanewtonMillimeterPerRadian = 6, + DecinewtonMeterPerDegree = 7, + DecinewtonMillimeterPerDegree = 8, + DecinewtonMillimeterPerRadian = 9, + KilonewtonMeterPerDegree = 10, + KilonewtonMeterPerRadian = 11, + KilonewtonMillimeterPerDegree = 12, + KilonewtonMillimeterPerRadian = 13, + KilopoundForceFootPerDegrees = 14, + MeganewtonMeterPerDegree = 15, + MeganewtonMeterPerRadian = 16, + MeganewtonMillimeterPerDegree = 17, + MeganewtonMillimeterPerRadian = 18, + MicronewtonMeterPerDegree = 19, + MicronewtonMillimeterPerDegree = 20, + MicronewtonMillimeterPerRadian = 21, + MillinewtonMeterPerDegree = 22, + MillinewtonMillimeterPerDegree = 23, + MillinewtonMillimeterPerRadian = 24, + NanonewtonMeterPerDegree = 25, + NanonewtonMillimeterPerDegree = 26, + NanonewtonMillimeterPerRadian = 27, + NewtonMeterPerDegree = 28, + NewtonMeterPerRadian = 29, + NewtonMillimeterPerDegree = 30, + NewtonMillimeterPerRadian = 31, + PoundForceFeetPerRadian = 32, + PoundForceFootPerDegrees = 33, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLength.csproj b/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLength.csproj new file mode 100644 index 0000000000..ed0e4ea625 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLength.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET RotationalStiffnessPerLength</Title> + <Description>Adds RotationalStiffnessPerLength units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>rotationalstiffnessperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{eae89113-1312-f83c-1a4b-638b98e760b3}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.RotationalStiffnessPerLength</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLength.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLength.g.cs new file mode 100644 index 0000000000..bf257e596c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLength.g.cs @@ -0,0 +1,922 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness + /// </summary> + [DataContract] + public readonly partial struct RotationalStiffnessPerLength : IArithmeticQuantity<RotationalStiffnessPerLength, RotationalStiffnessPerLengthUnit, double>, IEquatable<RotationalStiffnessPerLength>, IComparable, IComparable<RotationalStiffnessPerLength>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly RotationalStiffnessPerLengthUnit? _unit; + + static RotationalStiffnessPerLength() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + BaseUnit = RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; + Units = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast<RotationalStiffnessPerLengthUnit>().ToArray(); + Zero = new RotationalStiffnessPerLength(0, BaseUnit); + Info = new QuantityInfo<RotationalStiffnessPerLengthUnit>("RotationalStiffnessPerLength", + new UnitInfo<RotationalStiffnessPerLengthUnit>[] + { + new UnitInfo<RotationalStiffnessPerLengthUnit>(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, "KilonewtonMetersPerRadianPerMeter", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessPerLengthUnit>(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, "KilopoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessPerLengthUnit>(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, "MeganewtonMetersPerRadianPerMeter", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessPerLengthUnit>(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, "NewtonMetersPerRadianPerMeter", BaseUnits.Undefined), + new UnitInfo<RotationalStiffnessPerLengthUnit>(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "PoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public RotationalStiffnessPerLength(double value, RotationalStiffnessPerLengthUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="RotationalStiffnessPerLength" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<RotationalStiffnessPerLengthUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. + /// </summary> + public static RotationalStiffnessPerLengthUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the RotationalStiffnessPerLength quantity. + /// </summary> + public static RotationalStiffnessPerLengthUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. + /// </summary> + public static RotationalStiffnessPerLength Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static RotationalStiffnessPerLength AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<RotationalStiffnessPerLengthUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter"/> + /// </summary> + public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot"/> + /// </summary> + public double KilopoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter"/> + /// </summary> + public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter"/> + /// </summary> + public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot"/> + /// </summary> + public double PoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: RotationalStiffnessPerLengthUnit -> BaseUnit + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> RotationalStiffnessPerLengthUnit + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot)); + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter)); + unitConverter.SetConversionFunction<RotationalStiffnessPerLength>(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kN·m/rad/m", "kNm/rad/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf·ft/°/ft", "kip·ft/°/ft", "k·ft/°/ft", "kipf·ft/deg/ft", "kip·ft/deg/ft", "k·ft/deg/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, new CultureInfo("en-US"), false, true, new string[]{"MN·m/rad/m", "MNm/rad/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, new CultureInfo("en-US"), false, true, new string[]{"N·m/rad/m", "Nm/rad/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf·ft/deg/ft"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="RotationalStiffnessPerLength"/> from <see cref="RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue kilonewtonmetersperradianpermeter) + { + double value = (double) kilonewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffnessPerLength"/> from <see cref="RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFeet(QuantityValue kilopoundforcefeetperdegreesperfeet) + { + double value = (double) kilopoundforcefeetperdegreesperfeet; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffnessPerLength"/> from <see cref="RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue meganewtonmetersperradianpermeter) + { + double value = (double) meganewtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffnessPerLength"/> from <see cref="RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue newtonmetersperradianpermeter) + { + double value = (double) newtonmetersperradianpermeter; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + } + + /// <summary> + /// Creates a <see cref="RotationalStiffnessPerLength"/> from <see cref="RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(QuantityValue poundforcefeetperdegreesperfeet) + { + double value = (double) poundforcefeetperdegreesperfeet; + return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="RotationalStiffnessPerLengthUnit" /> to <see cref="RotationalStiffnessPerLength" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>RotationalStiffnessPerLength unit value.</returns> + public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) + { + return new RotationalStiffnessPerLength((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static RotationalStiffnessPerLength Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static RotationalStiffnessPerLength Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<RotationalStiffnessPerLength, RotationalStiffnessPerLengthUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out RotationalStiffnessPerLength result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out RotationalStiffnessPerLength result) + { + return QuantityParser.Default.TryParse<RotationalStiffnessPerLength, RotationalStiffnessPerLengthUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalStiffnessPerLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<RotationalStiffnessPerLengthUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.RotationalStiffnessPerLengthUnit)"/> + public static bool TryParseUnit(string str, out RotationalStiffnessPerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out RotationalStiffnessPerLengthUnit unit) + { + return UnitParser.Default.TryParse<RotationalStiffnessPerLengthUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static RotationalStiffnessPerLength operator -(RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalStiffnessPerLength"/> from adding two <see cref="RotationalStiffnessPerLength"/>.</summary> + public static RotationalStiffnessPerLength operator +(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalStiffnessPerLength"/> from subtracting two <see cref="RotationalStiffnessPerLength"/>.</summary> + public static RotationalStiffnessPerLength operator -(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="RotationalStiffnessPerLength"/> from multiplying value and <see cref="RotationalStiffnessPerLength"/>.</summary> + public static RotationalStiffnessPerLength operator *(double left, RotationalStiffnessPerLength right) + { + return new RotationalStiffnessPerLength(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="RotationalStiffnessPerLength"/> from multiplying value and <see cref="RotationalStiffnessPerLength"/>.</summary> + public static RotationalStiffnessPerLength operator *(RotationalStiffnessPerLength left, double right) + { + return new RotationalStiffnessPerLength(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="RotationalStiffnessPerLength"/> from dividing <see cref="RotationalStiffnessPerLength"/> by value.</summary> + public static RotationalStiffnessPerLength operator /(RotationalStiffnessPerLength left, double right) + { + return new RotationalStiffnessPerLength(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="RotationalStiffnessPerLength"/> by <see cref="RotationalStiffnessPerLength"/>.</summary> + public static double operator /(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.NewtonMetersPerRadianPerMeter / right.NewtonMetersPerRadianPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="RotationalStiffnessPerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffnessPerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="RotationalStiffnessPerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffnessPerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalStiffnessPerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffnessPerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is RotationalStiffnessPerLength otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="RotationalStiffnessPerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(RotationalStiffnessPerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(RotationalStiffnessPerLength other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="RotationalStiffnessPerLength"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is RotationalStiffnessPerLength otherQuantity)) throw new ArgumentException("Expected type RotationalStiffnessPerLength.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="RotationalStiffnessPerLength"/> with another <see cref="RotationalStiffnessPerLength"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(RotationalStiffnessPerLength other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another RotationalStiffnessPerLength within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current RotationalStiffnessPerLength.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(RotationalStiffnessPerLengthUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is RotationalStiffnessPerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A RotationalStiffnessPerLength with the specified unit.</returns> + public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="RotationalStiffnessPerLength"/> to another <see cref="RotationalStiffnessPerLength"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A RotationalStiffnessPerLength with the specified unit.</returns> + public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(RotationalStiffnessPerLength), Unit, typeof(RotationalStiffnessPerLength), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (RotationalStiffnessPerLength)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="RotationalStiffnessPerLength"/> to another <see cref="RotationalStiffnessPerLength"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="RotationalStiffnessPerLength"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(RotationalStiffnessPerLengthUnit unit, [NotNullWhen(true)] out RotationalStiffnessPerLength? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + RotationalStiffnessPerLength? convertedOrNull = (Unit, unit) switch + { + // RotationalStiffnessPerLengthUnit -> BaseUnit + (RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) * 1e3d, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), + (RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength(_value * 254864.324570, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), + (RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) * 1e6d, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), + (RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength(_value * 254.864324570, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), + + // BaseUnit -> RotationalStiffnessPerLengthUnit + (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) / 1e3d, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter), + (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot) => new RotationalStiffnessPerLength(_value / 254864.324570, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot), + (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) / 1e6d, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter), + (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot) => new RotationalStiffnessPerLength(_value / 254.864324570, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is RotationalStiffnessPerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<RotationalStiffnessPerLengthUnit> IQuantity<RotationalStiffnessPerLengthUnit>.ToUnit(RotationalStiffnessPerLengthUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<RotationalStiffnessPerLengthUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(RotationalStiffnessPerLength)) + return this; + else if (conversionType == typeof(RotationalStiffnessPerLengthUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return RotationalStiffnessPerLength.Info; + else if (conversionType == typeof(BaseDimensions)) + return RotationalStiffnessPerLength.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLengthUnit.g.cs b/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLengthUnit.g.cs new file mode 100644 index 0000000000..3829297d44 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/RotationalStiffnessPerLength/RotationalStiffnessPerLengthUnit.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum RotationalStiffnessPerLengthUnit + { + KilonewtonMeterPerRadianPerMeter = 1, + KilopoundForceFootPerDegreesPerFoot = 2, + MeganewtonMeterPerRadianPerMeter = 3, + NewtonMeterPerRadianPerMeter = 4, + PoundForceFootPerDegreesPerFoot = 5, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Scalar/Scalar.csproj b/UnitsNet.Modular/GeneratedCode/Scalar/Scalar.csproj new file mode 100644 index 0000000000..32ab4514b6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Scalar/Scalar.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Scalar</Title> + <Description>Adds Scalar units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>scalar unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{609c8143-bdb3-709b-a7a5-cc33659c9b51}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Scalar</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Scalar/Scalar.g.cs b/UnitsNet.Modular/GeneratedCode/Scalar/Scalar.g.cs new file mode 100644 index 0000000000..41e52330c5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Scalar/Scalar.g.cs @@ -0,0 +1,838 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// A way of representing a number of items. + /// </summary> + [DataContract] + public readonly partial struct Scalar : IArithmeticQuantity<Scalar, ScalarUnit, double>, IEquatable<Scalar>, IComparable, IComparable<Scalar>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ScalarUnit? _unit; + + static Scalar() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = ScalarUnit.Amount; + Units = Enum.GetValues(typeof(ScalarUnit)).Cast<ScalarUnit>().ToArray(); + Zero = new Scalar(0, BaseUnit); + Info = new QuantityInfo<ScalarUnit>("Scalar", + new UnitInfo<ScalarUnit>[] + { + new UnitInfo<ScalarUnit>(ScalarUnit.Amount, "Amount", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Scalar(double value, ScalarUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Scalar" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ScalarUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Scalar, which is Amount. All conversions go via this value. + /// </summary> + public static ScalarUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Scalar quantity. + /// </summary> + public static ScalarUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Amount. + /// </summary> + public static Scalar Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Scalar AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ScalarUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ScalarUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Scalar.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ScalarUnit.Amount"/> + /// </summary> + public double Amount => As(ScalarUnit.Amount); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ScalarUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Scalar>(ScalarUnit.Amount, ScalarUnit.Amount, quantity => quantity); + + // Register in unit converter: BaseUnit -> ScalarUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ScalarUnit.Amount, new CultureInfo("en-US"), false, true, new string[]{""}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ScalarUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ScalarUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Scalar"/> from <see cref="ScalarUnit.Amount"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Scalar FromAmount(QuantityValue amount) + { + double value = (double) amount; + return new Scalar(value, ScalarUnit.Amount); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ScalarUnit" /> to <see cref="Scalar" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Scalar unit value.</returns> + public static Scalar From(QuantityValue value, ScalarUnit fromUnit) + { + return new Scalar((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Scalar Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Scalar Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Scalar, ScalarUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Scalar result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Scalar result) + { + return QuantityParser.Default.TryParse<Scalar, ScalarUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ScalarUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ScalarUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ScalarUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ScalarUnit)"/> + public static bool TryParseUnit(string str, out ScalarUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ScalarUnit unit) + { + return UnitParser.Default.TryParse<ScalarUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Scalar operator -(Scalar right) + { + return new Scalar(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Scalar"/> from adding two <see cref="Scalar"/>.</summary> + public static Scalar operator +(Scalar left, Scalar right) + { + return new Scalar(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Scalar"/> from subtracting two <see cref="Scalar"/>.</summary> + public static Scalar operator -(Scalar left, Scalar right) + { + return new Scalar(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Scalar"/> from multiplying value and <see cref="Scalar"/>.</summary> + public static Scalar operator *(double left, Scalar right) + { + return new Scalar(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Scalar"/> from multiplying value and <see cref="Scalar"/>.</summary> + public static Scalar operator *(Scalar left, double right) + { + return new Scalar(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Scalar"/> from dividing <see cref="Scalar"/> by value.</summary> + public static Scalar operator /(Scalar left, double right) + { + return new Scalar(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Scalar"/> by <see cref="Scalar"/>.</summary> + public static double operator /(Scalar left, Scalar right) + { + return left.Amount / right.Amount; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Scalar left, Scalar right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Scalar left, Scalar right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Scalar left, Scalar right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Scalar left, Scalar right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Scalar"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Scalar left, Scalar right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Scalar"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Scalar left, Scalar right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Scalar"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Scalar otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Scalar"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Scalar other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Scalar"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Scalar otherQuantity)) throw new ArgumentException("Expected type Scalar.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Scalar"/> with another <see cref="Scalar"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Scalar other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Scalar within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Scalar other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Scalar.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ScalarUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ScalarUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Scalar to another Scalar with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Scalar with the specified unit.</returns> + public Scalar ToUnit(ScalarUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Scalar"/> to another <see cref="Scalar"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Scalar with the specified unit.</returns> + public Scalar ToUnit(ScalarUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Scalar), Unit, typeof(Scalar), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Scalar)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Scalar"/> to another <see cref="Scalar"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Scalar"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ScalarUnit unit, [NotNullWhen(true)] out Scalar? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Scalar? convertedOrNull = (Unit, unit) switch + { + // ScalarUnit -> BaseUnit + + // BaseUnit -> ScalarUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ScalarUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ScalarUnit> IQuantity<ScalarUnit>.ToUnit(ScalarUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ScalarUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Scalar)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Scalar)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Scalar)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Scalar)) + return this; + else if (conversionType == typeof(ScalarUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Scalar.Info; + else if (conversionType == typeof(BaseDimensions)) + return Scalar.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Scalar)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Scalar/ScalarUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Scalar/ScalarUnit.g.cs new file mode 100644 index 0000000000..c8be591b38 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Scalar/ScalarUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ScalarUnit + { + Amount = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngle.csproj b/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngle.csproj new file mode 100644 index 0000000000..9773f41c0a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngle.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET SolidAngle</Title> + <Description>Adds SolidAngle units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>solidangle unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{39d13fa7-a1df-cea6-adee-bab64a00a843}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.SolidAngle</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngle.g.cs b/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngle.g.cs new file mode 100644 index 0000000000..8a0a620710 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngle.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Solid_angle + /// </remarks> + [DataContract] + public readonly partial struct SolidAngle : IArithmeticQuantity<SolidAngle, SolidAngleUnit, double>, IEquatable<SolidAngle>, IComparable, IComparable<SolidAngle>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SolidAngleUnit? _unit; + + static SolidAngle() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = SolidAngleUnit.Steradian; + Units = Enum.GetValues(typeof(SolidAngleUnit)).Cast<SolidAngleUnit>().ToArray(); + Zero = new SolidAngle(0, BaseUnit); + Info = new QuantityInfo<SolidAngleUnit>("SolidAngle", + new UnitInfo<SolidAngleUnit>[] + { + new UnitInfo<SolidAngleUnit>(SolidAngleUnit.Steradian, "Steradians", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public SolidAngle(double value, SolidAngleUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="SolidAngle" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SolidAngleUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. + /// </summary> + public static SolidAngleUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the SolidAngle quantity. + /// </summary> + public static SolidAngleUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. + /// </summary> + public static SolidAngle Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static SolidAngle AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SolidAngleUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => SolidAngle.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SolidAngleUnit.Steradian"/> + /// </summary> + public double Steradians => As(SolidAngleUnit.Steradian); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SolidAngleUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<SolidAngle>(SolidAngleUnit.Steradian, SolidAngleUnit.Steradian, quantity => quantity); + + // Register in unit converter: BaseUnit -> SolidAngleUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SolidAngleUnit.Steradian, new CultureInfo("en-US"), false, true, new string[]{"sr"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SolidAngleUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SolidAngleUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="SolidAngle"/> from <see cref="SolidAngleUnit.Steradian"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SolidAngle FromSteradians(QuantityValue steradians) + { + double value = (double) steradians; + return new SolidAngle(value, SolidAngleUnit.Steradian); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SolidAngleUnit" /> to <see cref="SolidAngle" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>SolidAngle unit value.</returns> + public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) + { + return new SolidAngle((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static SolidAngle Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static SolidAngle Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<SolidAngle, SolidAngleUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out SolidAngle result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out SolidAngle result) + { + return QuantityParser.Default.TryParse<SolidAngle, SolidAngleUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SolidAngleUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SolidAngleUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SolidAngleUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SolidAngleUnit)"/> + public static bool TryParseUnit(string str, out SolidAngleUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SolidAngleUnit unit) + { + return UnitParser.Default.TryParse<SolidAngleUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static SolidAngle operator -(SolidAngle right) + { + return new SolidAngle(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="SolidAngle"/> from adding two <see cref="SolidAngle"/>.</summary> + public static SolidAngle operator +(SolidAngle left, SolidAngle right) + { + return new SolidAngle(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SolidAngle"/> from subtracting two <see cref="SolidAngle"/>.</summary> + public static SolidAngle operator -(SolidAngle left, SolidAngle right) + { + return new SolidAngle(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SolidAngle"/> from multiplying value and <see cref="SolidAngle"/>.</summary> + public static SolidAngle operator *(double left, SolidAngle right) + { + return new SolidAngle(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="SolidAngle"/> from multiplying value and <see cref="SolidAngle"/>.</summary> + public static SolidAngle operator *(SolidAngle left, double right) + { + return new SolidAngle(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="SolidAngle"/> from dividing <see cref="SolidAngle"/> by value.</summary> + public static SolidAngle operator /(SolidAngle left, double right) + { + return new SolidAngle(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="SolidAngle"/> by <see cref="SolidAngle"/>.</summary> + public static double operator /(SolidAngle left, SolidAngle right) + { + return left.Steradians / right.Steradians; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(SolidAngle left, SolidAngle right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(SolidAngle left, SolidAngle right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(SolidAngle left, SolidAngle right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(SolidAngle left, SolidAngle right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="SolidAngle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SolidAngle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(SolidAngle left, SolidAngle right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="SolidAngle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SolidAngle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(SolidAngle left, SolidAngle right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SolidAngle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SolidAngle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is SolidAngle otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SolidAngle"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SolidAngle, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(SolidAngle other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="SolidAngle"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is SolidAngle otherQuantity)) throw new ArgumentException("Expected type SolidAngle.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="SolidAngle"/> with another <see cref="SolidAngle"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(SolidAngle other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another SolidAngle within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current SolidAngle.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SolidAngleUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SolidAngleUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this SolidAngle to another SolidAngle with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A SolidAngle with the specified unit.</returns> + public SolidAngle ToUnit(SolidAngleUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="SolidAngle"/> to another <see cref="SolidAngle"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A SolidAngle with the specified unit.</returns> + public SolidAngle ToUnit(SolidAngleUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(SolidAngle), Unit, typeof(SolidAngle), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (SolidAngle)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="SolidAngle"/> to another <see cref="SolidAngle"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="SolidAngle"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SolidAngleUnit unit, [NotNullWhen(true)] out SolidAngle? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + SolidAngle? convertedOrNull = (Unit, unit) switch + { + // SolidAngleUnit -> BaseUnit + + // BaseUnit -> SolidAngleUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SolidAngleUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SolidAngleUnit> IQuantity<SolidAngleUnit>.ToUnit(SolidAngleUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SolidAngleUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SolidAngle)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SolidAngle)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SolidAngle)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(SolidAngle)) + return this; + else if (conversionType == typeof(SolidAngleUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return SolidAngle.Info; + else if (conversionType == typeof(BaseDimensions)) + return SolidAngle.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(SolidAngle)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngleUnit.g.cs b/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngleUnit.g.cs new file mode 100644 index 0000000000..7be81ae1a0 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SolidAngle/SolidAngleUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SolidAngleUnit + { + Steradian = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergy.csproj b/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergy.csproj new file mode 100644 index 0000000000..8b85dc65d9 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET SpecificEnergy</Title> + <Description>Adds SpecificEnergy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>specificenergy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5bce25ab-a4d6-d89c-5274-7eadd8c5967a}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.SpecificEnergy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergy.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergy.g.cs new file mode 100644 index 0000000000..45b5afcf50 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergy.g.cs @@ -0,0 +1,1429 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The SpecificEnergy + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Specific_energy + /// </remarks> + [DataContract] + public readonly partial struct SpecificEnergy : IArithmeticQuantity<SpecificEnergy, SpecificEnergyUnit, double>, IEquatable<SpecificEnergy>, IComparable, IComparable<SpecificEnergy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SpecificEnergyUnit? _unit; + + static SpecificEnergy() + { + BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); + BaseUnit = SpecificEnergyUnit.JoulePerKilogram; + Units = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast<SpecificEnergyUnit>().ToArray(); + Zero = new SpecificEnergy(0, BaseUnit); + Info = new QuantityInfo<SpecificEnergyUnit>("SpecificEnergy", + new UnitInfo<SpecificEnergyUnit>[] + { + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.BtuPerPound, "BtuPerPound", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.CaloriePerGram, "CaloriesPerGram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.GigawattDayPerKilogram, "GigawattDaysPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.GigawattDayPerShortTon, "GigawattDaysPerShortTon", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.GigawattDayPerTonne, "GigawattDaysPerTonne", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.GigawattHourPerKilogram, "GigawattHoursPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.GigawattHourPerPound, "GigawattHoursPerPound", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.JoulePerKilogram, "JoulesPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilocaloriePerGram, "KilocaloriesPerGram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilojoulePerKilogram, "KilojoulesPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilowattDayPerKilogram, "KilowattDaysPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilowattDayPerShortTon, "KilowattDaysPerShortTon", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilowattDayPerTonne, "KilowattDaysPerTonne", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilowattHourPerKilogram, "KilowattHoursPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.KilowattHourPerPound, "KilowattHoursPerPound", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.MegajoulePerKilogram, "MegajoulesPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.MegawattDayPerKilogram, "MegawattDaysPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.MegawattDayPerShortTon, "MegawattDaysPerShortTon", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.MegawattDayPerTonne, "MegawattDaysPerTonne", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.MegawattHourPerKilogram, "MegawattHoursPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.MegawattHourPerPound, "MegawattHoursPerPound", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.TerawattDayPerKilogram, "TerawattDaysPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.TerawattDayPerShortTon, "TerawattDaysPerShortTon", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.TerawattDayPerTonne, "TerawattDaysPerTonne", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.WattDayPerKilogram, "WattDaysPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.WattDayPerShortTon, "WattDaysPerShortTon", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.WattDayPerTonne, "WattDaysPerTonne", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.WattHourPerKilogram, "WattHoursPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificEnergyUnit>(SpecificEnergyUnit.WattHourPerPound, "WattHoursPerPound", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public SpecificEnergy(double value, SpecificEnergyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="SpecificEnergy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SpecificEnergyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. + /// </summary> + public static SpecificEnergyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the SpecificEnergy quantity. + /// </summary> + public static SpecificEnergyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. + /// </summary> + public static SpecificEnergy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static SpecificEnergy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SpecificEnergyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.BtuPerPound"/> + /// </summary> + public double BtuPerPound => As(SpecificEnergyUnit.BtuPerPound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.CaloriePerGram"/> + /// </summary> + public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.GigawattDayPerKilogram"/> + /// </summary> + public double GigawattDaysPerKilogram => As(SpecificEnergyUnit.GigawattDayPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.GigawattDayPerShortTon"/> + /// </summary> + public double GigawattDaysPerShortTon => As(SpecificEnergyUnit.GigawattDayPerShortTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.GigawattDayPerTonne"/> + /// </summary> + public double GigawattDaysPerTonne => As(SpecificEnergyUnit.GigawattDayPerTonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.GigawattHourPerKilogram"/> + /// </summary> + public double GigawattHoursPerKilogram => As(SpecificEnergyUnit.GigawattHourPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.GigawattHourPerPound"/> + /// </summary> + public double GigawattHoursPerPound => As(SpecificEnergyUnit.GigawattHourPerPound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.JoulePerKilogram"/> + /// </summary> + public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilocaloriePerGram"/> + /// </summary> + public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilojoulePerKilogram"/> + /// </summary> + public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilowattDayPerKilogram"/> + /// </summary> + public double KilowattDaysPerKilogram => As(SpecificEnergyUnit.KilowattDayPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilowattDayPerShortTon"/> + /// </summary> + public double KilowattDaysPerShortTon => As(SpecificEnergyUnit.KilowattDayPerShortTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilowattDayPerTonne"/> + /// </summary> + public double KilowattDaysPerTonne => As(SpecificEnergyUnit.KilowattDayPerTonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilowattHourPerKilogram"/> + /// </summary> + public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.KilowattHourPerPound"/> + /// </summary> + public double KilowattHoursPerPound => As(SpecificEnergyUnit.KilowattHourPerPound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.MegajoulePerKilogram"/> + /// </summary> + public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.MegawattDayPerKilogram"/> + /// </summary> + public double MegawattDaysPerKilogram => As(SpecificEnergyUnit.MegawattDayPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.MegawattDayPerShortTon"/> + /// </summary> + public double MegawattDaysPerShortTon => As(SpecificEnergyUnit.MegawattDayPerShortTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.MegawattDayPerTonne"/> + /// </summary> + public double MegawattDaysPerTonne => As(SpecificEnergyUnit.MegawattDayPerTonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.MegawattHourPerKilogram"/> + /// </summary> + public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.MegawattHourPerPound"/> + /// </summary> + public double MegawattHoursPerPound => As(SpecificEnergyUnit.MegawattHourPerPound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.TerawattDayPerKilogram"/> + /// </summary> + public double TerawattDaysPerKilogram => As(SpecificEnergyUnit.TerawattDayPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.TerawattDayPerShortTon"/> + /// </summary> + public double TerawattDaysPerShortTon => As(SpecificEnergyUnit.TerawattDayPerShortTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.TerawattDayPerTonne"/> + /// </summary> + public double TerawattDaysPerTonne => As(SpecificEnergyUnit.TerawattDayPerTonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.WattDayPerKilogram"/> + /// </summary> + public double WattDaysPerKilogram => As(SpecificEnergyUnit.WattDayPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.WattDayPerShortTon"/> + /// </summary> + public double WattDaysPerShortTon => As(SpecificEnergyUnit.WattDayPerShortTon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.WattDayPerTonne"/> + /// </summary> + public double WattDaysPerTonne => As(SpecificEnergyUnit.WattDayPerTonne); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.WattHourPerKilogram"/> + /// </summary> + public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEnergyUnit.WattHourPerPound"/> + /// </summary> + public double WattHoursPerPound => As(SpecificEnergyUnit.WattHourPerPound); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SpecificEnergyUnit -> BaseUnit + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.BtuPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.CaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.GigawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.GigawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.GigawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.GigawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.GigawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilocaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilojoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilowattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilowattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilowattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilowattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.KilowattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.MegajoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.MegawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.MegawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.MegawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.MegawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.MegawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.TerawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.TerawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.TerawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.WattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.WattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.WattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.WattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.WattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity); + + // Register in unit converter: BaseUnit -> SpecificEnergyUnit + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.BtuPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.BtuPerPound)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.CaloriePerGram, quantity => quantity.ToUnit(SpecificEnergyUnit.CaloriePerGram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerShortTon)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerTonne)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattHourPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattHourPerPound)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilocaloriePerGram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilocaloriePerGram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilojoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilojoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerShortTon)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerTonne)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattHourPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattHourPerPound)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegajoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegajoulePerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerShortTon)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerTonne)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattHourPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattHourPerPound)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerShortTon)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerTonne)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerShortTon)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerTonne)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.WattHourPerKilogram)); + unitConverter.SetConversionFunction<SpecificEnergy>(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.WattHourPerPound)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.BtuPerPound, new CultureInfo("en-US"), false, true, new string[]{"btu/lb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.CaloriePerGram, new CultureInfo("en-US"), false, true, new string[]{"cal/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.GigawattDayPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"GWd/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.GigawattDayPerShortTon, new CultureInfo("en-US"), false, true, new string[]{"GWd/ST"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.GigawattDayPerTonne, new CultureInfo("en-US"), false, true, new string[]{"GWd/t"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.GigawattHourPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"GWh/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.GigawattHourPerPound, new CultureInfo("en-US"), false, true, new string[]{"GWh/lbs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.JoulePerKilogram, new CultureInfo("en-US"), false, true, new string[]{"J/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilocaloriePerGram, new CultureInfo("en-US"), false, true, new string[]{"kcal/g"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilojoulePerKilogram, new CultureInfo("en-US"), false, true, new string[]{"kJ/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilowattDayPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"kWd/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilowattDayPerShortTon, new CultureInfo("en-US"), false, true, new string[]{"kWd/ST"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilowattDayPerTonne, new CultureInfo("en-US"), false, true, new string[]{"kWd/t"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilowattHourPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"kWh/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.KilowattHourPerPound, new CultureInfo("en-US"), false, true, new string[]{"kWh/lbs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.MegajoulePerKilogram, new CultureInfo("en-US"), false, true, new string[]{"MJ/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.MegawattDayPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"MWd/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.MegawattDayPerShortTon, new CultureInfo("en-US"), false, true, new string[]{"MWd/ST"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.MegawattDayPerTonne, new CultureInfo("en-US"), false, true, new string[]{"MWd/t"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.MegawattHourPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"MWh/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.MegawattHourPerPound, new CultureInfo("en-US"), false, true, new string[]{"MWh/lbs"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.TerawattDayPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"TWd/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.TerawattDayPerShortTon, new CultureInfo("en-US"), false, true, new string[]{"TWd/ST"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.TerawattDayPerTonne, new CultureInfo("en-US"), false, true, new string[]{"TWd/t"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.WattDayPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"Wd/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.WattDayPerShortTon, new CultureInfo("en-US"), false, true, new string[]{"Wd/ST"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.WattDayPerTonne, new CultureInfo("en-US"), false, true, new string[]{"Wd/t"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.WattHourPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"Wh/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEnergyUnit.WattHourPerPound, new CultureInfo("en-US"), false, true, new string[]{"Wh/lbs"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SpecificEnergyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SpecificEnergyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.BtuPerPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromBtuPerPound(QuantityValue btuperpound) + { + double value = (double) btuperpound; + return new SpecificEnergy(value, SpecificEnergyUnit.BtuPerPound); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.CaloriePerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) + { + double value = (double) caloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.GigawattDayPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromGigawattDaysPerKilogram(QuantityValue gigawattdaysperkilogram) + { + double value = (double) gigawattdaysperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.GigawattDayPerShortTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromGigawattDaysPerShortTon(QuantityValue gigawattdayspershortton) + { + double value = (double) gigawattdayspershortton; + return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerShortTon); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.GigawattDayPerTonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromGigawattDaysPerTonne(QuantityValue gigawattdayspertonne) + { + double value = (double) gigawattdayspertonne; + return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerTonne); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.GigawattHourPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromGigawattHoursPerKilogram(QuantityValue gigawatthoursperkilogram) + { + double value = (double) gigawatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.GigawattHourPerPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromGigawattHoursPerPound(QuantityValue gigawatthoursperpound) + { + double value = (double) gigawatthoursperpound; + return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerPound); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.JoulePerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) + { + double value = (double) joulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilocaloriePerGram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) + { + double value = (double) kilocaloriespergram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilojoulePerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) + { + double value = (double) kilojoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilowattDayPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilowattDaysPerKilogram(QuantityValue kilowattdaysperkilogram) + { + double value = (double) kilowattdaysperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilowattDayPerShortTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilowattDaysPerShortTon(QuantityValue kilowattdayspershortton) + { + double value = (double) kilowattdayspershortton; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerShortTon); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilowattDayPerTonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilowattDaysPerTonne(QuantityValue kilowattdayspertonne) + { + double value = (double) kilowattdayspertonne; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerTonne); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilowattHourPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) + { + double value = (double) kilowatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.KilowattHourPerPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromKilowattHoursPerPound(QuantityValue kilowatthoursperpound) + { + double value = (double) kilowatthoursperpound; + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerPound); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.MegajoulePerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) + { + double value = (double) megajoulesperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.MegawattDayPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromMegawattDaysPerKilogram(QuantityValue megawattdaysperkilogram) + { + double value = (double) megawattdaysperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.MegawattDayPerShortTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromMegawattDaysPerShortTon(QuantityValue megawattdayspershortton) + { + double value = (double) megawattdayspershortton; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerShortTon); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.MegawattDayPerTonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromMegawattDaysPerTonne(QuantityValue megawattdayspertonne) + { + double value = (double) megawattdayspertonne; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerTonne); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.MegawattHourPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) + { + double value = (double) megawatthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.MegawattHourPerPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromMegawattHoursPerPound(QuantityValue megawatthoursperpound) + { + double value = (double) megawatthoursperpound; + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerPound); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.TerawattDayPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromTerawattDaysPerKilogram(QuantityValue terawattdaysperkilogram) + { + double value = (double) terawattdaysperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.TerawattDayPerShortTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromTerawattDaysPerShortTon(QuantityValue terawattdayspershortton) + { + double value = (double) terawattdayspershortton; + return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerShortTon); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.TerawattDayPerTonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromTerawattDaysPerTonne(QuantityValue terawattdayspertonne) + { + double value = (double) terawattdayspertonne; + return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerTonne); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.WattDayPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromWattDaysPerKilogram(QuantityValue wattdaysperkilogram) + { + double value = (double) wattdaysperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.WattDayPerShortTon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromWattDaysPerShortTon(QuantityValue wattdayspershortton) + { + double value = (double) wattdayspershortton; + return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerShortTon); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.WattDayPerTonne"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromWattDaysPerTonne(QuantityValue wattdayspertonne) + { + double value = (double) wattdayspertonne; + return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerTonne); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.WattHourPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) + { + double value = (double) watthoursperkilogram; + return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificEnergy"/> from <see cref="SpecificEnergyUnit.WattHourPerPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEnergy FromWattHoursPerPound(QuantityValue watthoursperpound) + { + double value = (double) watthoursperpound; + return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerPound); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SpecificEnergyUnit" /> to <see cref="SpecificEnergy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>SpecificEnergy unit value.</returns> + public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) + { + return new SpecificEnergy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static SpecificEnergy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static SpecificEnergy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<SpecificEnergy, SpecificEnergyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out SpecificEnergy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out SpecificEnergy result) + { + return QuantityParser.Default.TryParse<SpecificEnergy, SpecificEnergyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificEnergyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificEnergyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SpecificEnergyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SpecificEnergyUnit)"/> + public static bool TryParseUnit(string str, out SpecificEnergyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificEnergyUnit unit) + { + return UnitParser.Default.TryParse<SpecificEnergyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static SpecificEnergy operator -(SpecificEnergy right) + { + return new SpecificEnergy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificEnergy"/> from adding two <see cref="SpecificEnergy"/>.</summary> + public static SpecificEnergy operator +(SpecificEnergy left, SpecificEnergy right) + { + return new SpecificEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificEnergy"/> from subtracting two <see cref="SpecificEnergy"/>.</summary> + public static SpecificEnergy operator -(SpecificEnergy left, SpecificEnergy right) + { + return new SpecificEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificEnergy"/> from multiplying value and <see cref="SpecificEnergy"/>.</summary> + public static SpecificEnergy operator *(double left, SpecificEnergy right) + { + return new SpecificEnergy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificEnergy"/> from multiplying value and <see cref="SpecificEnergy"/>.</summary> + public static SpecificEnergy operator *(SpecificEnergy left, double right) + { + return new SpecificEnergy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="SpecificEnergy"/> from dividing <see cref="SpecificEnergy"/> by value.</summary> + public static SpecificEnergy operator /(SpecificEnergy left, double right) + { + return new SpecificEnergy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="SpecificEnergy"/> by <see cref="SpecificEnergy"/>.</summary> + public static double operator /(SpecificEnergy left, SpecificEnergy right) + { + return left.JoulesPerKilogram / right.JoulesPerKilogram; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(SpecificEnergy left, SpecificEnergy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(SpecificEnergy left, SpecificEnergy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(SpecificEnergy left, SpecificEnergy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(SpecificEnergy left, SpecificEnergy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="SpecificEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(SpecificEnergy left, SpecificEnergy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="SpecificEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(SpecificEnergy left, SpecificEnergy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is SpecificEnergy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificEnergy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEnergy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(SpecificEnergy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="SpecificEnergy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is SpecificEnergy otherQuantity)) throw new ArgumentException("Expected type SpecificEnergy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="SpecificEnergy"/> with another <see cref="SpecificEnergy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(SpecificEnergy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another SpecificEnergy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current SpecificEnergy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SpecificEnergyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SpecificEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A SpecificEnergy with the specified unit.</returns> + public SpecificEnergy ToUnit(SpecificEnergyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="SpecificEnergy"/> to another <see cref="SpecificEnergy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A SpecificEnergy with the specified unit.</returns> + public SpecificEnergy ToUnit(SpecificEnergyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(SpecificEnergy), Unit, typeof(SpecificEnergy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (SpecificEnergy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="SpecificEnergy"/> to another <see cref="SpecificEnergy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="SpecificEnergy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SpecificEnergyUnit unit, [NotNullWhen(true)] out SpecificEnergy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + SpecificEnergy? convertedOrNull = (Unit, unit) switch + { + // SpecificEnergyUnit -> BaseUnit + (SpecificEnergyUnit.BtuPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 2326.000075362, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.CaloriePerGram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 4.184e3, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.GigawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.GigawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.GigawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.GigawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 3.6e3) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.GigawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 7.93664e3) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilocaloriePerGram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 4.184e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilojoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilowattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilowattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilowattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilowattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 3.6e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.KilowattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 7.93664e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.MegajoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.MegawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.MegawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.MegawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.MegawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 3.6e3) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.MegawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 7.93664e3) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.TerawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.TerawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.TerawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.WattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * (24 * 3.6e3), SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.WattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * ((24 * 3.6e3) / 9.0718474e2), SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.WattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * ((24 * 3.6e3) / 1e3), SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.WattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 3.6e3, SpecificEnergyUnit.JoulePerKilogram), + (SpecificEnergyUnit.WattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 7.93664e3, SpecificEnergyUnit.JoulePerKilogram), + + // BaseUnit -> SpecificEnergyUnit + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.BtuPerPound) => new SpecificEnergy(_value / 2326.000075362, SpecificEnergyUnit.BtuPerPound), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.CaloriePerGram) => new SpecificEnergy(_value / 4.184e3, SpecificEnergyUnit.CaloriePerGram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e9d, SpecificEnergyUnit.GigawattDayPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e9d, SpecificEnergyUnit.GigawattDayPerShortTon), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e9d, SpecificEnergyUnit.GigawattDayPerTonne), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerKilogram) => new SpecificEnergy((_value / 3.6e3) / 1e9d, SpecificEnergyUnit.GigawattHourPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerPound) => new SpecificEnergy((_value / 7.93664e3) / 1e9d, SpecificEnergyUnit.GigawattHourPerPound), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilocaloriePerGram) => new SpecificEnergy((_value / 4.184e3) / 1e3d, SpecificEnergyUnit.KilocaloriePerGram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilojoulePerKilogram) => new SpecificEnergy((_value) / 1e3d, SpecificEnergyUnit.KilojoulePerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e3d, SpecificEnergyUnit.KilowattDayPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e3d, SpecificEnergyUnit.KilowattDayPerShortTon), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e3d, SpecificEnergyUnit.KilowattDayPerTonne), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerKilogram) => new SpecificEnergy((_value / 3.6e3) / 1e3d, SpecificEnergyUnit.KilowattHourPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerPound) => new SpecificEnergy((_value / 7.93664e3) / 1e3d, SpecificEnergyUnit.KilowattHourPerPound), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegajoulePerKilogram) => new SpecificEnergy((_value) / 1e6d, SpecificEnergyUnit.MegajoulePerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e6d, SpecificEnergyUnit.MegawattDayPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e6d, SpecificEnergyUnit.MegawattDayPerShortTon), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e6d, SpecificEnergyUnit.MegawattDayPerTonne), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerKilogram) => new SpecificEnergy((_value / 3.6e3) / 1e6d, SpecificEnergyUnit.MegawattHourPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerPound) => new SpecificEnergy((_value / 7.93664e3) / 1e6d, SpecificEnergyUnit.MegawattHourPerPound), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e12d, SpecificEnergyUnit.TerawattDayPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e12d, SpecificEnergyUnit.TerawattDayPerShortTon), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e12d, SpecificEnergyUnit.TerawattDayPerTonne), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerKilogram) => new SpecificEnergy(_value / (24 * 3.6e3), SpecificEnergyUnit.WattDayPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerShortTon) => new SpecificEnergy(_value / ((24 * 3.6e3) / 9.0718474e2), SpecificEnergyUnit.WattDayPerShortTon), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerTonne) => new SpecificEnergy(_value / ((24 * 3.6e3) / 1e3), SpecificEnergyUnit.WattDayPerTonne), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerKilogram) => new SpecificEnergy(_value / 3.6e3, SpecificEnergyUnit.WattHourPerKilogram), + (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerPound) => new SpecificEnergy(_value / 7.93664e3, SpecificEnergyUnit.WattHourPerPound), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SpecificEnergyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SpecificEnergyUnit> IQuantity<SpecificEnergyUnit>.ToUnit(SpecificEnergyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SpecificEnergyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(SpecificEnergy)) + return this; + else if (conversionType == typeof(SpecificEnergyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return SpecificEnergy.Info; + else if (conversionType == typeof(BaseDimensions)) + return SpecificEnergy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergyUnit.g.cs new file mode 100644 index 0000000000..85d8161f49 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificEnergy/SpecificEnergyUnit.g.cs @@ -0,0 +1,60 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SpecificEnergyUnit + { + BtuPerPound = 1, + CaloriePerGram = 2, + GigawattDayPerKilogram = 3, + GigawattDayPerShortTon = 4, + GigawattDayPerTonne = 5, + GigawattHourPerKilogram = 6, + GigawattHourPerPound = 7, + JoulePerKilogram = 8, + KilocaloriePerGram = 9, + KilojoulePerKilogram = 10, + KilowattDayPerKilogram = 11, + KilowattDayPerShortTon = 12, + KilowattDayPerTonne = 13, + KilowattHourPerKilogram = 14, + KilowattHourPerPound = 15, + MegajoulePerKilogram = 16, + MegawattDayPerKilogram = 17, + MegawattDayPerShortTon = 18, + MegawattDayPerTonne = 19, + MegawattHourPerKilogram = 20, + MegawattHourPerPound = 21, + TerawattDayPerKilogram = 22, + TerawattDayPerShortTon = 23, + TerawattDayPerTonne = 24, + WattDayPerKilogram = 25, + WattDayPerShortTon = 26, + WattDayPerTonne = 27, + WattHourPerKilogram = 28, + WattHourPerPound = 29, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropy.csproj b/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropy.csproj new file mode 100644 index 0000000000..8051b8d039 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropy.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET SpecificEntropy</Title> + <Description>Adds SpecificEntropy units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>specificentropy unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{0d5dc515-9d35-ac02-c0b1-12c70c3163a2}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.SpecificEntropy</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropy.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropy.g.cs new file mode 100644 index 0000000000..ac740ea6e4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropy.g.cs @@ -0,0 +1,1006 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. + /// </summary> + [DataContract] + public readonly partial struct SpecificEntropy : IArithmeticQuantity<SpecificEntropy, SpecificEntropyUnit, double>, IEquatable<SpecificEntropy>, IComparable, IComparable<SpecificEntropy>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SpecificEntropyUnit? _unit; + + static SpecificEntropy() + { + BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); + BaseUnit = SpecificEntropyUnit.JoulePerKilogramKelvin; + Units = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast<SpecificEntropyUnit>().ToArray(); + Zero = new SpecificEntropy(0, BaseUnit); + Info = new QuantityInfo<SpecificEntropyUnit>("SpecificEntropy", + new UnitInfo<SpecificEntropyUnit>[] + { + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.BtuPerPoundFahrenheit, "BtusPerPoundFahrenheit", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.CaloriePerGramKelvin, "CaloriesPerGramKelvin", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, "JoulesPerKilogramDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.JoulePerKilogramKelvin, "JoulesPerKilogramKelvin", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.KilocaloriePerGramKelvin, "KilocaloriesPerGramKelvin", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, "KilojoulesPerKilogramDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.KilojoulePerKilogramKelvin, "KilojoulesPerKilogramKelvin", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, "MegajoulesPerKilogramDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<SpecificEntropyUnit>(SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MegajoulesPerKilogramKelvin", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public SpecificEntropy(double value, SpecificEntropyUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="SpecificEntropy" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SpecificEntropyUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. + /// </summary> + public static SpecificEntropyUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the SpecificEntropy quantity. + /// </summary> + public static SpecificEntropyUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. + /// </summary> + public static SpecificEntropy Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static SpecificEntropy AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SpecificEntropyUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.BtuPerPoundFahrenheit"/> + /// </summary> + public double BtusPerPoundFahrenheit => As(SpecificEntropyUnit.BtuPerPoundFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.CaloriePerGramKelvin"/> + /// </summary> + public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.JoulePerKilogramDegreeCelsius"/> + /// </summary> + public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.JoulePerKilogramKelvin"/> + /// </summary> + public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.KilocaloriePerGramKelvin"/> + /// </summary> + public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius"/> + /// </summary> + public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.KilojoulePerKilogramKelvin"/> + /// </summary> + public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius"/> + /// </summary> + public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificEntropyUnit.MegajoulePerKilogramKelvin"/> + /// </summary> + public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SpecificEntropyUnit -> BaseUnit + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.BtuPerPoundFahrenheit, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.CaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.KilocaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.KilojoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.MegajoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> SpecificEntropyUnit + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.BtuPerPoundFahrenheit, quantity => quantity.ToUnit(SpecificEntropyUnit.BtuPerPoundFahrenheit)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.CaloriePerGramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.CaloriePerGramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilocaloriePerGramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.KilocaloriePerGramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramKelvin)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius)); + unitConverter.SetConversionFunction<SpecificEntropy>(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramKelvin)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.BtuPerPoundFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"BTU/lb·°F", "BTU/lbm·°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.CaloriePerGramKelvin, new CultureInfo("en-US"), false, true, new string[]{"cal/g.K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"J/kg.C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.JoulePerKilogramKelvin, new CultureInfo("en-US"), false, true, new string[]{"J/kg.K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.KilocaloriePerGramKelvin, new CultureInfo("en-US"), false, true, new string[]{"kcal/g.K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"kJ/kg.C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.KilojoulePerKilogramKelvin, new CultureInfo("en-US"), false, true, new string[]{"kJ/kg.K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"MJ/kg.C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificEntropyUnit.MegajoulePerKilogramKelvin, new CultureInfo("en-US"), false, true, new string[]{"MJ/kg.K"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SpecificEntropyUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SpecificEntropyUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.BtuPerPoundFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromBtusPerPoundFahrenheit(QuantityValue btusperpoundfahrenheit) + { + double value = (double) btusperpoundfahrenheit; + return new SpecificEntropy(value, SpecificEntropyUnit.BtuPerPoundFahrenheit); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.CaloriePerGramKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) + { + double value = (double) caloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.JoulePerKilogramDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) + { + double value = (double) joulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.JoulePerKilogramKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) + { + double value = (double) joulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.KilocaloriePerGramKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) + { + double value = (double) kilocaloriespergramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) + { + double value = (double) kilojoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.KilojoulePerKilogramKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) + { + double value = (double) kilojoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) + { + double value = (double) megajoulesperkilogramdegreecelsius; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="SpecificEntropy"/> from <see cref="SpecificEntropyUnit.MegajoulePerKilogramKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) + { + double value = (double) megajoulesperkilogramkelvin; + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SpecificEntropyUnit" /> to <see cref="SpecificEntropy" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>SpecificEntropy unit value.</returns> + public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) + { + return new SpecificEntropy((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static SpecificEntropy Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static SpecificEntropy Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<SpecificEntropy, SpecificEntropyUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out SpecificEntropy result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out SpecificEntropy result) + { + return QuantityParser.Default.TryParse<SpecificEntropy, SpecificEntropyUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificEntropyUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificEntropyUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SpecificEntropyUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SpecificEntropyUnit)"/> + public static bool TryParseUnit(string str, out SpecificEntropyUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificEntropyUnit unit) + { + return UnitParser.Default.TryParse<SpecificEntropyUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static SpecificEntropy operator -(SpecificEntropy right) + { + return new SpecificEntropy(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificEntropy"/> from adding two <see cref="SpecificEntropy"/>.</summary> + public static SpecificEntropy operator +(SpecificEntropy left, SpecificEntropy right) + { + return new SpecificEntropy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificEntropy"/> from subtracting two <see cref="SpecificEntropy"/>.</summary> + public static SpecificEntropy operator -(SpecificEntropy left, SpecificEntropy right) + { + return new SpecificEntropy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificEntropy"/> from multiplying value and <see cref="SpecificEntropy"/>.</summary> + public static SpecificEntropy operator *(double left, SpecificEntropy right) + { + return new SpecificEntropy(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificEntropy"/> from multiplying value and <see cref="SpecificEntropy"/>.</summary> + public static SpecificEntropy operator *(SpecificEntropy left, double right) + { + return new SpecificEntropy(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="SpecificEntropy"/> from dividing <see cref="SpecificEntropy"/> by value.</summary> + public static SpecificEntropy operator /(SpecificEntropy left, double right) + { + return new SpecificEntropy(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="SpecificEntropy"/> by <see cref="SpecificEntropy"/>.</summary> + public static double operator /(SpecificEntropy left, SpecificEntropy right) + { + return left.JoulesPerKilogramKelvin / right.JoulesPerKilogramKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(SpecificEntropy left, SpecificEntropy right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(SpecificEntropy left, SpecificEntropy right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(SpecificEntropy left, SpecificEntropy right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(SpecificEntropy left, SpecificEntropy right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="SpecificEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(SpecificEntropy left, SpecificEntropy right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="SpecificEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(SpecificEntropy left, SpecificEntropy right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is SpecificEntropy otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificEntropy"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificEntropy, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(SpecificEntropy other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="SpecificEntropy"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is SpecificEntropy otherQuantity)) throw new ArgumentException("Expected type SpecificEntropy.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="SpecificEntropy"/> with another <see cref="SpecificEntropy"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(SpecificEntropy other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another SpecificEntropy within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current SpecificEntropy.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SpecificEntropyUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SpecificEntropyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A SpecificEntropy with the specified unit.</returns> + public SpecificEntropy ToUnit(SpecificEntropyUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="SpecificEntropy"/> to another <see cref="SpecificEntropy"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A SpecificEntropy with the specified unit.</returns> + public SpecificEntropy ToUnit(SpecificEntropyUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(SpecificEntropy), Unit, typeof(SpecificEntropy), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (SpecificEntropy)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="SpecificEntropy"/> to another <see cref="SpecificEntropy"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="SpecificEntropy"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SpecificEntropyUnit unit, [NotNullWhen(true)] out SpecificEntropy? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + SpecificEntropy? convertedOrNull = (Unit, unit) switch + { + // SpecificEntropyUnit -> BaseUnit + (SpecificEntropyUnit.BtuPerPoundFahrenheit, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy(_value * 4.1868e3, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.CaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy(_value * 4.184e3, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy(_value, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.KilocaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value * 4.184e3) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.KilojoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e6d, SpecificEntropyUnit.JoulePerKilogramKelvin), + (SpecificEntropyUnit.MegajoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e6d, SpecificEntropyUnit.JoulePerKilogramKelvin), + + // BaseUnit -> SpecificEntropyUnit + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.BtuPerPoundFahrenheit) => new SpecificEntropy(_value / 4.1868e3, SpecificEntropyUnit.BtuPerPoundFahrenheit), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.CaloriePerGramKelvin) => new SpecificEntropy(_value / 4.184e3, SpecificEntropyUnit.CaloriePerGramKelvin), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius) => new SpecificEntropy(_value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilocaloriePerGramKelvin) => new SpecificEntropy((_value / 4.184e3) / 1e3d, SpecificEntropyUnit.KilocaloriePerGramKelvin), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius) => new SpecificEntropy((_value) / 1e3d, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramKelvin) => new SpecificEntropy((_value) / 1e3d, SpecificEntropyUnit.KilojoulePerKilogramKelvin), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius) => new SpecificEntropy((_value) / 1e6d, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius), + (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramKelvin) => new SpecificEntropy((_value) / 1e6d, SpecificEntropyUnit.MegajoulePerKilogramKelvin), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SpecificEntropyUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SpecificEntropyUnit> IQuantity<SpecificEntropyUnit>.ToUnit(SpecificEntropyUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SpecificEntropyUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(SpecificEntropy)) + return this; + else if (conversionType == typeof(SpecificEntropyUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return SpecificEntropy.Info; + else if (conversionType == typeof(BaseDimensions)) + return SpecificEntropy.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropyUnit.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropyUnit.g.cs new file mode 100644 index 0000000000..77e55a2af2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificEntropy/SpecificEntropyUnit.g.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SpecificEntropyUnit + { + BtuPerPoundFahrenheit = 1, + CaloriePerGramKelvin = 2, + JoulePerKilogramDegreeCelsius = 3, + JoulePerKilogramKelvin = 4, + KilocaloriePerGramKelvin = 5, + KilojoulePerKilogramDegreeCelsius = 6, + KilojoulePerKilogramKelvin = 7, + MegajoulePerKilogramDegreeCelsius = 8, + MegajoulePerKilogramKelvin = 9, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumption.csproj b/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumption.csproj new file mode 100644 index 0000000000..acae16b79b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumption.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET SpecificFuelConsumption</Title> + <Description>Adds SpecificFuelConsumption units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>specificfuelconsumption unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{f1a91b9a-ec32-5f98-d4d6-75ac04c63276}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.SpecificFuelConsumption</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumption.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumption.g.cs new file mode 100644 index 0000000000..e5c04f6b24 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumption.g.cs @@ -0,0 +1,904 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// SFC is the fuel efficiency of an engine design with respect to thrust output + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Thrust-specific_fuel_consumption + /// </remarks> + [DataContract] + public readonly partial struct SpecificFuelConsumption : IArithmeticQuantity<SpecificFuelConsumption, SpecificFuelConsumptionUnit, double>, IEquatable<SpecificFuelConsumption>, IComparable, IComparable<SpecificFuelConsumption>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SpecificFuelConsumptionUnit? _unit; + + static SpecificFuelConsumption() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond; + Units = Enum.GetValues(typeof(SpecificFuelConsumptionUnit)).Cast<SpecificFuelConsumptionUnit>().ToArray(); + Zero = new SpecificFuelConsumption(0, BaseUnit); + Info = new QuantityInfo<SpecificFuelConsumptionUnit>("SpecificFuelConsumption", + new UnitInfo<SpecificFuelConsumptionUnit>[] + { + new UnitInfo<SpecificFuelConsumptionUnit>(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, "GramsPerKiloNewtonSecond", BaseUnits.Undefined), + new UnitInfo<SpecificFuelConsumptionUnit>(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, "KilogramsPerKilogramForceHour", BaseUnits.Undefined), + new UnitInfo<SpecificFuelConsumptionUnit>(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, "KilogramsPerKiloNewtonSecond", BaseUnits.Undefined), + new UnitInfo<SpecificFuelConsumptionUnit>(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "PoundsMassPerPoundForceHour", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public SpecificFuelConsumption(double value, SpecificFuelConsumptionUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="SpecificFuelConsumption" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SpecificFuelConsumptionUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of SpecificFuelConsumption, which is GramPerKiloNewtonSecond. All conversions go via this value. + /// </summary> + public static SpecificFuelConsumptionUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the SpecificFuelConsumption quantity. + /// </summary> + public static SpecificFuelConsumptionUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit GramPerKiloNewtonSecond. + /// </summary> + public static SpecificFuelConsumption Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static SpecificFuelConsumption AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SpecificFuelConsumptionUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => SpecificFuelConsumption.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond"/> + /// </summary> + public double GramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour"/> + /// </summary> + public double KilogramsPerKilogramForceHour => As(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond"/> + /// </summary> + public double KilogramsPerKiloNewtonSecond => As(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour"/> + /// </summary> + public double PoundsMassPerPoundForceHour => As(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SpecificFuelConsumptionUnit -> BaseUnit + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond)); + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond)); + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> SpecificFuelConsumptionUnit + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour)); + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond)); + unitConverter.SetConversionFunction<SpecificFuelConsumption>(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, new CultureInfo("en-US"), false, true, new string[]{"g/(kN�s)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, new CultureInfo("en-US"), false, true, new string[]{"kg/(kgf�h)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, new CultureInfo("en-US"), false, true, new string[]{"kg/(kN�s)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, new CultureInfo("en-US"), false, true, new string[]{"lb/(lbf·h)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SpecificFuelConsumptionUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SpecificFuelConsumptionUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="SpecificFuelConsumption"/> from <see cref="SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificFuelConsumption FromGramsPerKiloNewtonSecond(QuantityValue gramsperkilonewtonsecond) + { + double value = (double) gramsperkilonewtonsecond; + return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond); + } + + /// <summary> + /// Creates a <see cref="SpecificFuelConsumption"/> from <see cref="SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(QuantityValue kilogramsperkilogramforcehour) + { + double value = (double) kilogramsperkilogramforcehour; + return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); + } + + /// <summary> + /// Creates a <see cref="SpecificFuelConsumption"/> from <see cref="SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificFuelConsumption FromKilogramsPerKiloNewtonSecond(QuantityValue kilogramsperkilonewtonsecond) + { + double value = (double) kilogramsperkilonewtonsecond; + return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond); + } + + /// <summary> + /// Creates a <see cref="SpecificFuelConsumption"/> from <see cref="SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(QuantityValue poundsmassperpoundforcehour) + { + double value = (double) poundsmassperpoundforcehour; + return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SpecificFuelConsumptionUnit" /> to <see cref="SpecificFuelConsumption" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>SpecificFuelConsumption unit value.</returns> + public static SpecificFuelConsumption From(QuantityValue value, SpecificFuelConsumptionUnit fromUnit) + { + return new SpecificFuelConsumption((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static SpecificFuelConsumption Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static SpecificFuelConsumption Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<SpecificFuelConsumption, SpecificFuelConsumptionUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out SpecificFuelConsumption result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out SpecificFuelConsumption result) + { + return QuantityParser.Default.TryParse<SpecificFuelConsumption, SpecificFuelConsumptionUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificFuelConsumptionUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SpecificFuelConsumptionUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SpecificFuelConsumptionUnit)"/> + public static bool TryParseUnit(string str, out SpecificFuelConsumptionUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificFuelConsumptionUnit unit) + { + return UnitParser.Default.TryParse<SpecificFuelConsumptionUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static SpecificFuelConsumption operator -(SpecificFuelConsumption right) + { + return new SpecificFuelConsumption(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificFuelConsumption"/> from adding two <see cref="SpecificFuelConsumption"/>.</summary> + public static SpecificFuelConsumption operator +(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return new SpecificFuelConsumption(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificFuelConsumption"/> from subtracting two <see cref="SpecificFuelConsumption"/>.</summary> + public static SpecificFuelConsumption operator -(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return new SpecificFuelConsumption(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificFuelConsumption"/> from multiplying value and <see cref="SpecificFuelConsumption"/>.</summary> + public static SpecificFuelConsumption operator *(double left, SpecificFuelConsumption right) + { + return new SpecificFuelConsumption(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificFuelConsumption"/> from multiplying value and <see cref="SpecificFuelConsumption"/>.</summary> + public static SpecificFuelConsumption operator *(SpecificFuelConsumption left, double right) + { + return new SpecificFuelConsumption(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="SpecificFuelConsumption"/> from dividing <see cref="SpecificFuelConsumption"/> by value.</summary> + public static SpecificFuelConsumption operator /(SpecificFuelConsumption left, double right) + { + return new SpecificFuelConsumption(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="SpecificFuelConsumption"/> by <see cref="SpecificFuelConsumption"/>.</summary> + public static double operator /(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.GramsPerKiloNewtonSecond / right.GramsPerKiloNewtonSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="SpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="SpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(SpecificFuelConsumption left, SpecificFuelConsumption right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is SpecificFuelConsumption otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificFuelConsumption"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificFuelConsumption, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(SpecificFuelConsumption other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="SpecificFuelConsumption"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is SpecificFuelConsumption otherQuantity)) throw new ArgumentException("Expected type SpecificFuelConsumption.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="SpecificFuelConsumption"/> with another <see cref="SpecificFuelConsumption"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(SpecificFuelConsumption other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another SpecificFuelConsumption within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(SpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current SpecificFuelConsumption.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SpecificFuelConsumptionUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SpecificFuelConsumptionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this SpecificFuelConsumption to another SpecificFuelConsumption with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A SpecificFuelConsumption with the specified unit.</returns> + public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="SpecificFuelConsumption"/> to another <see cref="SpecificFuelConsumption"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A SpecificFuelConsumption with the specified unit.</returns> + public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(SpecificFuelConsumption), Unit, typeof(SpecificFuelConsumption), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (SpecificFuelConsumption)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="SpecificFuelConsumption"/> to another <see cref="SpecificFuelConsumption"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="SpecificFuelConsumption"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SpecificFuelConsumptionUnit unit, [NotNullWhen(true)] out SpecificFuelConsumption? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + SpecificFuelConsumption? convertedOrNull = (Unit, unit) switch + { + // SpecificFuelConsumptionUnit -> BaseUnit + (SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond) => new SpecificFuelConsumption(_value * 28.33, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond), + (SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond) => new SpecificFuelConsumption((_value) * 1e3d, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond), + (SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond) => new SpecificFuelConsumption(_value * 28.33, SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond), + + // BaseUnit -> SpecificFuelConsumptionUnit + (SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour) => new SpecificFuelConsumption(_value / 28.33, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour), + (SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond) => new SpecificFuelConsumption((_value) / 1e3d, SpecificFuelConsumptionUnit.KilogramPerKiloNewtonSecond), + (SpecificFuelConsumptionUnit.GramPerKiloNewtonSecond, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour) => new SpecificFuelConsumption(_value / 28.33, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SpecificFuelConsumptionUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SpecificFuelConsumptionUnit> IQuantity<SpecificFuelConsumptionUnit>.ToUnit(SpecificFuelConsumptionUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SpecificFuelConsumptionUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(SpecificFuelConsumption)) + return this; + else if (conversionType == typeof(SpecificFuelConsumptionUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return SpecificFuelConsumption.Info; + else if (conversionType == typeof(BaseDimensions)) + return SpecificFuelConsumption.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumptionUnit.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumptionUnit.g.cs new file mode 100644 index 0000000000..f647a17cf6 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificFuelConsumption/SpecificFuelConsumptionUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SpecificFuelConsumptionUnit + { + GramPerKiloNewtonSecond = 1, + KilogramPerKilogramForceHour = 2, + KilogramPerKiloNewtonSecond = 3, + PoundMassPerPoundForceHour = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolume.csproj b/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolume.csproj new file mode 100644 index 0000000000..edf706d234 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolume.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET SpecificVolume</Title> + <Description>Adds SpecificVolume units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>specificvolume unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{74b88d5c-96e5-7286-d2b2-8def18538246}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.SpecificVolume</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolume.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolume.g.cs new file mode 100644 index 0000000000..1f84934566 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolume.g.cs @@ -0,0 +1,880 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct SpecificVolume : IArithmeticQuantity<SpecificVolume, SpecificVolumeUnit, double>, IEquatable<SpecificVolume>, IComparable, IComparable<SpecificVolume>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SpecificVolumeUnit? _unit; + + static SpecificVolume() + { + BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); + BaseUnit = SpecificVolumeUnit.CubicMeterPerKilogram; + Units = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast<SpecificVolumeUnit>().ToArray(); + Zero = new SpecificVolume(0, BaseUnit); + Info = new QuantityInfo<SpecificVolumeUnit>("SpecificVolume", + new UnitInfo<SpecificVolumeUnit>[] + { + new UnitInfo<SpecificVolumeUnit>(SpecificVolumeUnit.CubicFootPerPound, "CubicFeetPerPound", BaseUnits.Undefined), + new UnitInfo<SpecificVolumeUnit>(SpecificVolumeUnit.CubicMeterPerKilogram, "CubicMetersPerKilogram", BaseUnits.Undefined), + new UnitInfo<SpecificVolumeUnit>(SpecificVolumeUnit.MillicubicMeterPerKilogram, "MillicubicMetersPerKilogram", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public SpecificVolume(double value, SpecificVolumeUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="SpecificVolume" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SpecificVolumeUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. + /// </summary> + public static SpecificVolumeUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the SpecificVolume quantity. + /// </summary> + public static SpecificVolumeUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. + /// </summary> + public static SpecificVolume Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static SpecificVolume AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SpecificVolumeUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificVolumeUnit.CubicFootPerPound"/> + /// </summary> + public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificVolumeUnit.CubicMeterPerKilogram"/> + /// </summary> + public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificVolumeUnit.MillicubicMeterPerKilogram"/> + /// </summary> + public double MillicubicMetersPerKilogram => As(SpecificVolumeUnit.MillicubicMeterPerKilogram); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SpecificVolumeUnit -> BaseUnit + unitConverter.SetConversionFunction<SpecificVolume>(SpecificVolumeUnit.CubicFootPerPound, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicMeterPerKilogram)); + unitConverter.SetConversionFunction<SpecificVolume>(SpecificVolumeUnit.MillicubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicMeterPerKilogram)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<SpecificVolume>(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity); + + // Register in unit converter: BaseUnit -> SpecificVolumeUnit + unitConverter.SetConversionFunction<SpecificVolume>(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicFootPerPound, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicFootPerPound)); + unitConverter.SetConversionFunction<SpecificVolume>(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.MillicubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.MillicubicMeterPerKilogram)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificVolumeUnit.CubicFootPerPound, new CultureInfo("en-US"), false, true, new string[]{"ft³/lb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificVolumeUnit.CubicMeterPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"m³/kg"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificVolumeUnit.MillicubicMeterPerKilogram, new CultureInfo("en-US"), false, true, new string[]{"mm³/kg"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SpecificVolumeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SpecificVolumeUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="SpecificVolume"/> from <see cref="SpecificVolumeUnit.CubicFootPerPound"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificVolume FromCubicFeetPerPound(QuantityValue cubicfeetperpound) + { + double value = (double) cubicfeetperpound; + return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); + } + + /// <summary> + /// Creates a <see cref="SpecificVolume"/> from <see cref="SpecificVolumeUnit.CubicMeterPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) + { + double value = (double) cubicmetersperkilogram; + return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); + } + + /// <summary> + /// Creates a <see cref="SpecificVolume"/> from <see cref="SpecificVolumeUnit.MillicubicMeterPerKilogram"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificVolume FromMillicubicMetersPerKilogram(QuantityValue millicubicmetersperkilogram) + { + double value = (double) millicubicmetersperkilogram; + return new SpecificVolume(value, SpecificVolumeUnit.MillicubicMeterPerKilogram); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SpecificVolumeUnit" /> to <see cref="SpecificVolume" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>SpecificVolume unit value.</returns> + public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) + { + return new SpecificVolume((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static SpecificVolume Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static SpecificVolume Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<SpecificVolume, SpecificVolumeUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out SpecificVolume result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out SpecificVolume result) + { + return QuantityParser.Default.TryParse<SpecificVolume, SpecificVolumeUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificVolumeUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificVolumeUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SpecificVolumeUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SpecificVolumeUnit)"/> + public static bool TryParseUnit(string str, out SpecificVolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificVolumeUnit unit) + { + return UnitParser.Default.TryParse<SpecificVolumeUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static SpecificVolume operator -(SpecificVolume right) + { + return new SpecificVolume(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificVolume"/> from adding two <see cref="SpecificVolume"/>.</summary> + public static SpecificVolume operator +(SpecificVolume left, SpecificVolume right) + { + return new SpecificVolume(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificVolume"/> from subtracting two <see cref="SpecificVolume"/>.</summary> + public static SpecificVolume operator -(SpecificVolume left, SpecificVolume right) + { + return new SpecificVolume(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificVolume"/> from multiplying value and <see cref="SpecificVolume"/>.</summary> + public static SpecificVolume operator *(double left, SpecificVolume right) + { + return new SpecificVolume(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificVolume"/> from multiplying value and <see cref="SpecificVolume"/>.</summary> + public static SpecificVolume operator *(SpecificVolume left, double right) + { + return new SpecificVolume(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="SpecificVolume"/> from dividing <see cref="SpecificVolume"/> by value.</summary> + public static SpecificVolume operator /(SpecificVolume left, double right) + { + return new SpecificVolume(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="SpecificVolume"/> by <see cref="SpecificVolume"/>.</summary> + public static double operator /(SpecificVolume left, SpecificVolume right) + { + return left.CubicMetersPerKilogram / right.CubicMetersPerKilogram; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(SpecificVolume left, SpecificVolume right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(SpecificVolume left, SpecificVolume right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(SpecificVolume left, SpecificVolume right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(SpecificVolume left, SpecificVolume right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="SpecificVolume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificVolume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(SpecificVolume left, SpecificVolume right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="SpecificVolume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificVolume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(SpecificVolume left, SpecificVolume right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificVolume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificVolume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is SpecificVolume otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificVolume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificVolume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(SpecificVolume other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="SpecificVolume"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is SpecificVolume otherQuantity)) throw new ArgumentException("Expected type SpecificVolume.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="SpecificVolume"/> with another <see cref="SpecificVolume"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(SpecificVolume other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another SpecificVolume within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current SpecificVolume.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SpecificVolumeUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SpecificVolumeUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this SpecificVolume to another SpecificVolume with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A SpecificVolume with the specified unit.</returns> + public SpecificVolume ToUnit(SpecificVolumeUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="SpecificVolume"/> to another <see cref="SpecificVolume"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A SpecificVolume with the specified unit.</returns> + public SpecificVolume ToUnit(SpecificVolumeUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(SpecificVolume), Unit, typeof(SpecificVolume), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (SpecificVolume)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="SpecificVolume"/> to another <see cref="SpecificVolume"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="SpecificVolume"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SpecificVolumeUnit unit, [NotNullWhen(true)] out SpecificVolume? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + SpecificVolume? convertedOrNull = (Unit, unit) switch + { + // SpecificVolumeUnit -> BaseUnit + (SpecificVolumeUnit.CubicFootPerPound, SpecificVolumeUnit.CubicMeterPerKilogram) => new SpecificVolume(_value / 16.01846353, SpecificVolumeUnit.CubicMeterPerKilogram), + (SpecificVolumeUnit.MillicubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram) => new SpecificVolume((_value) * 1e-3d, SpecificVolumeUnit.CubicMeterPerKilogram), + + // BaseUnit -> SpecificVolumeUnit + (SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicFootPerPound) => new SpecificVolume(_value * 16.01846353, SpecificVolumeUnit.CubicFootPerPound), + (SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.MillicubicMeterPerKilogram) => new SpecificVolume((_value) / 1e-3d, SpecificVolumeUnit.MillicubicMeterPerKilogram), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SpecificVolumeUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SpecificVolumeUnit> IQuantity<SpecificVolumeUnit>.ToUnit(SpecificVolumeUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SpecificVolumeUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(SpecificVolume)) + return this; + else if (conversionType == typeof(SpecificVolumeUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return SpecificVolume.Info; + else if (conversionType == typeof(BaseDimensions)) + return SpecificVolume.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolumeUnit.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolumeUnit.g.cs new file mode 100644 index 0000000000..49be37c632 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificVolume/SpecificVolumeUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SpecificVolumeUnit + { + CubicFootPerPound = 1, + CubicMeterPerKilogram = 2, + MillicubicMeterPerKilogram = 3, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeight.csproj b/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeight.csproj new file mode 100644 index 0000000000..f63d096cf1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeight.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET SpecificWeight</Title> + <Description>Adds SpecificWeight units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>specificweight unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{d63ac796-7087-bf6c-2848-e6511358fbe4}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.SpecificWeight</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeight.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeight.g.cs new file mode 100644 index 0000000000..ae11f91950 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeight.g.cs @@ -0,0 +1,1177 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume. + /// </summary> + /// <remarks> + /// http://en.wikipedia.org/wiki/Specificweight + /// </remarks> + [DataContract] + public readonly partial struct SpecificWeight : IArithmeticQuantity<SpecificWeight, SpecificWeightUnit, double>, IEquatable<SpecificWeight>, IComparable, IComparable<SpecificWeight>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SpecificWeightUnit? _unit; + + static SpecificWeight() + { + BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); + BaseUnit = SpecificWeightUnit.NewtonPerCubicMeter; + Units = Enum.GetValues(typeof(SpecificWeightUnit)).Cast<SpecificWeightUnit>().ToArray(); + Zero = new SpecificWeight(0, BaseUnit); + Info = new QuantityInfo<SpecificWeightUnit>("SpecificWeight", + new UnitInfo<SpecificWeightUnit>[] + { + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilogramForcePerCubicCentimeter, "KilogramsForcePerCubicCentimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilogramForcePerCubicMeter, "KilogramsForcePerCubicMeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilogramForcePerCubicMillimeter, "KilogramsForcePerCubicMillimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilonewtonPerCubicCentimeter, "KilonewtonsPerCubicCentimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilonewtonPerCubicMeter, "KilonewtonsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilonewtonPerCubicMillimeter, "KilonewtonsPerCubicMillimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilopoundForcePerCubicFoot, "KilopoundsForcePerCubicFoot", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.KilopoundForcePerCubicInch, "KilopoundsForcePerCubicInch", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.MeganewtonPerCubicMeter, "MeganewtonsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.NewtonPerCubicCentimeter, "NewtonsPerCubicCentimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.NewtonPerCubicMeter, "NewtonsPerCubicMeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.NewtonPerCubicMillimeter, "NewtonsPerCubicMillimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.PoundForcePerCubicFoot, "PoundsForcePerCubicFoot", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.PoundForcePerCubicInch, "PoundsForcePerCubicInch", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.TonneForcePerCubicCentimeter, "TonnesForcePerCubicCentimeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.TonneForcePerCubicMeter, "TonnesForcePerCubicMeter", BaseUnits.Undefined), + new UnitInfo<SpecificWeightUnit>(SpecificWeightUnit.TonneForcePerCubicMillimeter, "TonnesForcePerCubicMillimeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public SpecificWeight(double value, SpecificWeightUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="SpecificWeight" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SpecificWeightUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. + /// </summary> + public static SpecificWeightUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the SpecificWeight quantity. + /// </summary> + public static SpecificWeightUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. + /// </summary> + public static SpecificWeight Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static SpecificWeight AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SpecificWeightUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilogramForcePerCubicCentimeter"/> + /// </summary> + public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilogramForcePerCubicMeter"/> + /// </summary> + public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilogramForcePerCubicMillimeter"/> + /// </summary> + public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilonewtonPerCubicCentimeter"/> + /// </summary> + public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilonewtonPerCubicMeter"/> + /// </summary> + public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilonewtonPerCubicMillimeter"/> + /// </summary> + public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilopoundForcePerCubicFoot"/> + /// </summary> + public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.KilopoundForcePerCubicInch"/> + /// </summary> + public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.MeganewtonPerCubicMeter"/> + /// </summary> + public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.NewtonPerCubicCentimeter"/> + /// </summary> + public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.NewtonPerCubicMeter"/> + /// </summary> + public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.NewtonPerCubicMillimeter"/> + /// </summary> + public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.PoundForcePerCubicFoot"/> + /// </summary> + public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.PoundForcePerCubicInch"/> + /// </summary> + public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.TonneForcePerCubicCentimeter"/> + /// </summary> + public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.TonneForcePerCubicMeter"/> + /// </summary> + public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpecificWeightUnit.TonneForcePerCubicMillimeter"/> + /// </summary> + public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SpecificWeightUnit -> BaseUnit + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilogramForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilogramForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilogramForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilonewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilonewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilonewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilopoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.KilopoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.MeganewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.PoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.PoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.TonneForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.TonneForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.TonneForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> SpecificWeightUnit + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicCentimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMillimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicCentimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMillimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicFoot, quantity => quantity.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicFoot)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicInch, quantity => quantity.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicInch)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.MeganewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.MeganewtonPerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicCentimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMillimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicFoot, quantity => quantity.ToUnit(SpecificWeightUnit.PoundForcePerCubicFoot)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicInch, quantity => quantity.ToUnit(SpecificWeightUnit.PoundForcePerCubicInch)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicCentimeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicMeter)); + unitConverter.SetConversionFunction<SpecificWeight>(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilogramForcePerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilogramForcePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilogramForcePerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilonewtonPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kN/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilonewtonPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"kN/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilonewtonPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kN/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilopoundForcePerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.KilopoundForcePerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"kipf/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.MeganewtonPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"MN/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.NewtonPerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"N/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.NewtonPerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"N/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.NewtonPerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"N/mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.PoundForcePerCubicFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf/ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.PoundForcePerCubicInch, new CultureInfo("en-US"), false, true, new string[]{"lbf/in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.TonneForcePerCubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"tf/cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.TonneForcePerCubicMeter, new CultureInfo("en-US"), false, true, new string[]{"tf/m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpecificWeightUnit.TonneForcePerCubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"tf/mm³"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SpecificWeightUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SpecificWeightUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilogramForcePerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) + { + double value = (double) kilogramsforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilogramForcePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) + { + double value = (double) kilogramsforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilogramForcePerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) + { + double value = (double) kilogramsforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilonewtonPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) + { + double value = (double) kilonewtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilonewtonPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) + { + double value = (double) kilonewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilonewtonPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) + { + double value = (double) kilonewtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilopoundForcePerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) + { + double value = (double) kilopoundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.KilopoundForcePerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) + { + double value = (double) kilopoundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.MeganewtonPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue meganewtonspercubicmeter) + { + double value = (double) meganewtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.NewtonPerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) + { + double value = (double) newtonspercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.NewtonPerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) + { + double value = (double) newtonspercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.NewtonPerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) + { + double value = (double) newtonspercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.PoundForcePerCubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) + { + double value = (double) poundsforcepercubicfoot; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.PoundForcePerCubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) + { + double value = (double) poundsforcepercubicinch; + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.TonneForcePerCubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) + { + double value = (double) tonnesforcepercubiccentimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.TonneForcePerCubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) + { + double value = (double) tonnesforcepercubicmeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); + } + + /// <summary> + /// Creates a <see cref="SpecificWeight"/> from <see cref="SpecificWeightUnit.TonneForcePerCubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) + { + double value = (double) tonnesforcepercubicmillimeter; + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SpecificWeightUnit" /> to <see cref="SpecificWeight" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>SpecificWeight unit value.</returns> + public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) + { + return new SpecificWeight((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static SpecificWeight Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static SpecificWeight Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<SpecificWeight, SpecificWeightUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out SpecificWeight result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out SpecificWeight result) + { + return QuantityParser.Default.TryParse<SpecificWeight, SpecificWeightUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificWeightUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpecificWeightUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SpecificWeightUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SpecificWeightUnit)"/> + public static bool TryParseUnit(string str, out SpecificWeightUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SpecificWeightUnit unit) + { + return UnitParser.Default.TryParse<SpecificWeightUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static SpecificWeight operator -(SpecificWeight right) + { + return new SpecificWeight(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificWeight"/> from adding two <see cref="SpecificWeight"/>.</summary> + public static SpecificWeight operator +(SpecificWeight left, SpecificWeight right) + { + return new SpecificWeight(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificWeight"/> from subtracting two <see cref="SpecificWeight"/>.</summary> + public static SpecificWeight operator -(SpecificWeight left, SpecificWeight right) + { + return new SpecificWeight(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="SpecificWeight"/> from multiplying value and <see cref="SpecificWeight"/>.</summary> + public static SpecificWeight operator *(double left, SpecificWeight right) + { + return new SpecificWeight(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="SpecificWeight"/> from multiplying value and <see cref="SpecificWeight"/>.</summary> + public static SpecificWeight operator *(SpecificWeight left, double right) + { + return new SpecificWeight(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="SpecificWeight"/> from dividing <see cref="SpecificWeight"/> by value.</summary> + public static SpecificWeight operator /(SpecificWeight left, double right) + { + return new SpecificWeight(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="SpecificWeight"/> by <see cref="SpecificWeight"/>.</summary> + public static double operator /(SpecificWeight left, SpecificWeight right) + { + return left.NewtonsPerCubicMeter / right.NewtonsPerCubicMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(SpecificWeight left, SpecificWeight right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(SpecificWeight left, SpecificWeight right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(SpecificWeight left, SpecificWeight right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(SpecificWeight left, SpecificWeight right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="SpecificWeight"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificWeight, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(SpecificWeight left, SpecificWeight right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="SpecificWeight"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificWeight, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(SpecificWeight left, SpecificWeight right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificWeight"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificWeight, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is SpecificWeight otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="SpecificWeight"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(SpecificWeight, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(SpecificWeight other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="SpecificWeight"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is SpecificWeight otherQuantity)) throw new ArgumentException("Expected type SpecificWeight.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="SpecificWeight"/> with another <see cref="SpecificWeight"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(SpecificWeight other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another SpecificWeight within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current SpecificWeight.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SpecificWeightUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SpecificWeightUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this SpecificWeight to another SpecificWeight with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A SpecificWeight with the specified unit.</returns> + public SpecificWeight ToUnit(SpecificWeightUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="SpecificWeight"/> to another <see cref="SpecificWeight"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A SpecificWeight with the specified unit.</returns> + public SpecificWeight ToUnit(SpecificWeightUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(SpecificWeight), Unit, typeof(SpecificWeight), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (SpecificWeight)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="SpecificWeight"/> to another <see cref="SpecificWeight"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="SpecificWeight"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SpecificWeightUnit unit, [NotNullWhen(true)] out SpecificWeight? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + SpecificWeight? convertedOrNull = (Unit, unit) switch + { + // SpecificWeightUnit -> BaseUnit + (SpecificWeightUnit.KilogramForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e6, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilogramForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilogramForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e9, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilonewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 1000000) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilonewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilonewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 1000000000) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilopoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 1.570874638462462e2) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.KilopoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 2.714471375263134e5) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.MeganewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value) * 1e6d, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.NewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 1000000, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.NewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 1000000000, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.PoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 1.570874638462462e2, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.PoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 2.714471375263134e5, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.TonneForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e9, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.TonneForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e3, SpecificWeightUnit.NewtonPerCubicMeter), + (SpecificWeightUnit.TonneForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e12, SpecificWeightUnit.NewtonPerCubicMeter), + + // BaseUnit -> SpecificWeightUnit + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicCentimeter) => new SpecificWeight(_value / 9.80665e6, SpecificWeightUnit.KilogramForcePerCubicCentimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMeter) => new SpecificWeight(_value / 9.80665, SpecificWeightUnit.KilogramForcePerCubicMeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMillimeter) => new SpecificWeight(_value / 9.80665e9, SpecificWeightUnit.KilogramForcePerCubicMillimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicCentimeter) => new SpecificWeight((_value * 0.000001) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicCentimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMeter) => new SpecificWeight((_value) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicMeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMillimeter) => new SpecificWeight((_value * 0.000000001) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicMillimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicFoot) => new SpecificWeight((_value / 1.570874638462462e2) / 1e3d, SpecificWeightUnit.KilopoundForcePerCubicFoot), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicInch) => new SpecificWeight((_value / 2.714471375263134e5) / 1e3d, SpecificWeightUnit.KilopoundForcePerCubicInch), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.MeganewtonPerCubicMeter) => new SpecificWeight((_value) / 1e6d, SpecificWeightUnit.MeganewtonPerCubicMeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicCentimeter) => new SpecificWeight(_value * 0.000001, SpecificWeightUnit.NewtonPerCubicCentimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMillimeter) => new SpecificWeight(_value * 0.000000001, SpecificWeightUnit.NewtonPerCubicMillimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicFoot) => new SpecificWeight(_value / 1.570874638462462e2, SpecificWeightUnit.PoundForcePerCubicFoot), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicInch) => new SpecificWeight(_value / 2.714471375263134e5, SpecificWeightUnit.PoundForcePerCubicInch), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicCentimeter) => new SpecificWeight(_value / 9.80665e9, SpecificWeightUnit.TonneForcePerCubicCentimeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMeter) => new SpecificWeight(_value / 9.80665e3, SpecificWeightUnit.TonneForcePerCubicMeter), + (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMillimeter) => new SpecificWeight(_value / 9.80665e12, SpecificWeightUnit.TonneForcePerCubicMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SpecificWeightUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SpecificWeightUnit> IQuantity<SpecificWeightUnit>.ToUnit(SpecificWeightUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SpecificWeightUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(SpecificWeight)) + return this; + else if (conversionType == typeof(SpecificWeightUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return SpecificWeight.Info; + else if (conversionType == typeof(BaseDimensions)) + return SpecificWeight.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeightUnit.g.cs b/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeightUnit.g.cs new file mode 100644 index 0000000000..a4ff736200 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/SpecificWeight/SpecificWeightUnit.g.cs @@ -0,0 +1,48 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SpecificWeightUnit + { + KilogramForcePerCubicCentimeter = 1, + KilogramForcePerCubicMeter = 2, + KilogramForcePerCubicMillimeter = 3, + KilonewtonPerCubicCentimeter = 4, + KilonewtonPerCubicMeter = 5, + KilonewtonPerCubicMillimeter = 6, + KilopoundForcePerCubicFoot = 7, + KilopoundForcePerCubicInch = 8, + MeganewtonPerCubicMeter = 9, + NewtonPerCubicCentimeter = 10, + NewtonPerCubicMeter = 11, + NewtonPerCubicMillimeter = 12, + PoundForcePerCubicFoot = 13, + PoundForcePerCubicInch = 14, + TonneForcePerCubicCentimeter = 15, + TonneForcePerCubicMeter = 16, + TonneForcePerCubicMillimeter = 17, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Speed/Speed.csproj b/UnitsNet.Modular/GeneratedCode/Speed/Speed.csproj new file mode 100644 index 0000000000..2f6be0cc4c --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Speed/Speed.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Speed</Title> + <Description>Adds Speed units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>speed unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{e9fe72c3-56b4-856b-a592-ae6e98e571f3}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Speed</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Speed/Speed.g.cs b/UnitsNet.Modular/GeneratedCode/Speed/Speed.g.cs new file mode 100644 index 0000000000..ad99d405e3 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Speed/Speed.g.cs @@ -0,0 +1,1534 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Speed : IArithmeticQuantity<Speed, SpeedUnit, double>, IEquatable<Speed>, IComparable, IComparable<Speed>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly SpeedUnit? _unit; + + static Speed() + { + BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); + BaseUnit = SpeedUnit.MeterPerSecond; + Units = Enum.GetValues(typeof(SpeedUnit)).Cast<SpeedUnit>().ToArray(); + Zero = new Speed(0, BaseUnit); + Info = new QuantityInfo<SpeedUnit>("Speed", + new UnitInfo<SpeedUnit>[] + { + new UnitInfo<SpeedUnit>(SpeedUnit.CentimeterPerHour, "CentimetersPerHour", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.CentimeterPerMinute, "CentimetersPerMinutes", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.CentimeterPerSecond, "CentimetersPerSecond", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.DecimeterPerMinute, "DecimetersPerMinutes", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.DecimeterPerSecond, "DecimetersPerSecond", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.FootPerHour, "FeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.FootPerMinute, "FeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)), + new UnitInfo<SpeedUnit>(SpeedUnit.FootPerSecond, "FeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)), + new UnitInfo<SpeedUnit>(SpeedUnit.InchPerHour, "InchesPerHour", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.InchPerMinute, "InchesPerMinute", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Minute)), + new UnitInfo<SpeedUnit>(SpeedUnit.InchPerSecond, "InchesPerSecond", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second)), + new UnitInfo<SpeedUnit>(SpeedUnit.KilometerPerHour, "KilometersPerHour", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.KilometerPerMinute, "KilometersPerMinutes", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.KilometerPerSecond, "KilometersPerSecond", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.Knot, "Knots", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.Mach, "Mach", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.MeterPerHour, "MetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.MeterPerMinute, "MetersPerMinutes", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute)), + new UnitInfo<SpeedUnit>(SpeedUnit.MeterPerSecond, "MetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), + new UnitInfo<SpeedUnit>(SpeedUnit.MicrometerPerMinute, "MicrometersPerMinutes", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.MicrometerPerSecond, "MicrometersPerSecond", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.MilePerHour, "MilesPerHour", new BaseUnits(length: LengthUnit.Mile, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.MillimeterPerHour, "MillimetersPerHour", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.MillimeterPerMinute, "MillimetersPerMinutes", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.MillimeterPerSecond, "MillimetersPerSecond", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.NanometerPerMinute, "NanometersPerMinutes", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.NanometerPerSecond, "NanometersPerSecond", BaseUnits.Undefined), + new UnitInfo<SpeedUnit>(SpeedUnit.UsSurveyFootPerHour, "UsSurveyFeetPerHour", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.UsSurveyFootPerMinute, "UsSurveyFeetPerMinute", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Minute)), + new UnitInfo<SpeedUnit>(SpeedUnit.UsSurveyFootPerSecond, "UsSurveyFeetPerSecond", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Second)), + new UnitInfo<SpeedUnit>(SpeedUnit.YardPerHour, "YardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour)), + new UnitInfo<SpeedUnit>(SpeedUnit.YardPerMinute, "YardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute)), + new UnitInfo<SpeedUnit>(SpeedUnit.YardPerSecond, "YardsPerSecond", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Second)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Speed(double value, SpeedUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Speed" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<SpeedUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. + /// </summary> + public static SpeedUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Speed quantity. + /// </summary> + public static SpeedUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. + /// </summary> + public static Speed Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Speed AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<SpeedUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Speed.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.CentimeterPerHour"/> + /// </summary> + public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.CentimeterPerMinute"/> + /// </summary> + public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.CentimeterPerSecond"/> + /// </summary> + public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.DecimeterPerMinute"/> + /// </summary> + public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.DecimeterPerSecond"/> + /// </summary> + public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.FootPerHour"/> + /// </summary> + public double FeetPerHour => As(SpeedUnit.FootPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.FootPerMinute"/> + /// </summary> + public double FeetPerMinute => As(SpeedUnit.FootPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.FootPerSecond"/> + /// </summary> + public double FeetPerSecond => As(SpeedUnit.FootPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.InchPerHour"/> + /// </summary> + public double InchesPerHour => As(SpeedUnit.InchPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.InchPerMinute"/> + /// </summary> + public double InchesPerMinute => As(SpeedUnit.InchPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.InchPerSecond"/> + /// </summary> + public double InchesPerSecond => As(SpeedUnit.InchPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.KilometerPerHour"/> + /// </summary> + public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.KilometerPerMinute"/> + /// </summary> + public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.KilometerPerSecond"/> + /// </summary> + public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.Knot"/> + /// </summary> + public double Knots => As(SpeedUnit.Knot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.Mach"/> + /// </summary> + public double Mach => As(SpeedUnit.Mach); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MeterPerHour"/> + /// </summary> + public double MetersPerHour => As(SpeedUnit.MeterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MeterPerMinute"/> + /// </summary> + public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MeterPerSecond"/> + /// </summary> + public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MicrometerPerMinute"/> + /// </summary> + public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MicrometerPerSecond"/> + /// </summary> + public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MilePerHour"/> + /// </summary> + public double MilesPerHour => As(SpeedUnit.MilePerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MillimeterPerHour"/> + /// </summary> + public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MillimeterPerMinute"/> + /// </summary> + public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.MillimeterPerSecond"/> + /// </summary> + public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.NanometerPerMinute"/> + /// </summary> + public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.NanometerPerSecond"/> + /// </summary> + public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.UsSurveyFootPerHour"/> + /// </summary> + public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.UsSurveyFootPerMinute"/> + /// </summary> + public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.UsSurveyFootPerSecond"/> + /// </summary> + public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.YardPerHour"/> + /// </summary> + public double YardsPerHour => As(SpeedUnit.YardPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.YardPerMinute"/> + /// </summary> + public double YardsPerMinute => As(SpeedUnit.YardPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="SpeedUnit.YardPerSecond"/> + /// </summary> + public double YardsPerSecond => As(SpeedUnit.YardPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: SpeedUnit -> BaseUnit + unitConverter.SetConversionFunction<Speed>(SpeedUnit.CentimeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.CentimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.CentimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.DecimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.DecimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.FootPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.FootPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.FootPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.InchPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.InchPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.InchPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.KilometerPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.KilometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.KilometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.Knot, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.Mach, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MicrometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MicrometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MilePerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MillimeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MillimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MillimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.NanometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.NanometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.UsSurveyFootPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.UsSurveyFootPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.UsSurveyFootPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.YardPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.YardPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.YardPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> SpeedUnit + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerHour, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.DecimeterPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.DecimeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerHour, quantity => quantity.ToUnit(SpeedUnit.FootPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerMinute, quantity => quantity.ToUnit(SpeedUnit.FootPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerSecond, quantity => quantity.ToUnit(SpeedUnit.FootPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerHour, quantity => quantity.ToUnit(SpeedUnit.InchPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerMinute, quantity => quantity.ToUnit(SpeedUnit.InchPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerSecond, quantity => quantity.ToUnit(SpeedUnit.InchPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerHour, quantity => quantity.ToUnit(SpeedUnit.KilometerPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.KilometerPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.KilometerPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.Knot, quantity => quantity.ToUnit(SpeedUnit.Knot)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.Mach, quantity => quantity.ToUnit(SpeedUnit.Mach)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerHour, quantity => quantity.ToUnit(SpeedUnit.MeterPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.MeterPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.MicrometerPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.MicrometerPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MilePerHour, quantity => quantity.ToUnit(SpeedUnit.MilePerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerHour, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.NanometerPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.NanometerPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerHour, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerMinute, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerSecond, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerSecond)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerHour, quantity => quantity.ToUnit(SpeedUnit.YardPerHour)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerMinute, quantity => quantity.ToUnit(SpeedUnit.YardPerMinute)); + unitConverter.SetConversionFunction<Speed>(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerSecond, quantity => quantity.ToUnit(SpeedUnit.YardPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.CentimeterPerHour, new CultureInfo("en-US"), false, true, new string[]{"cm/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.CentimeterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"см/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.CentimeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"cm/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.CentimeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"см/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.CentimeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"cm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.CentimeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"см/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.DecimeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"dm/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.DecimeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"дм/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.DecimeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"dm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.DecimeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"дм/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.FootPerHour, new CultureInfo("en-US"), false, true, new string[]{"ft/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.FootPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"фут/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.FootPerMinute, new CultureInfo("en-US"), false, true, new string[]{"ft/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.FootPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"фут/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.FootPerSecond, new CultureInfo("en-US"), false, true, new string[]{"ft/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.FootPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"фут/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.InchPerHour, new CultureInfo("en-US"), false, true, new string[]{"in/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.InchPerMinute, new CultureInfo("en-US"), false, true, new string[]{"in/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.InchPerSecond, new CultureInfo("en-US"), false, true, new string[]{"in/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.KilometerPerHour, new CultureInfo("en-US"), false, true, new string[]{"km/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.KilometerPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"км/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.KilometerPerMinute, new CultureInfo("en-US"), false, true, new string[]{"km/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.KilometerPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"км/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.KilometerPerSecond, new CultureInfo("en-US"), false, true, new string[]{"km/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.KilometerPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"км/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.Knot, new CultureInfo("en-US"), false, true, new string[]{"kn", "kt", "knot", "knots"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.Knot, new CultureInfo("ru-RU"), false, true, new string[]{"уз."}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.Mach, new CultureInfo("en-US"), false, true, new string[]{"M", "Ma", "MN", "MACH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.Mach, new CultureInfo("ru-RU"), false, true, new string[]{"мах"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MeterPerHour, new CultureInfo("en-US"), false, true, new string[]{"m/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MeterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"м/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"m/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"м/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"m/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"м/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MicrometerPerMinute, new CultureInfo("en-US"), false, true, new string[]{"µm/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MicrometerPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"мкм/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MicrometerPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MicrometerPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мкм/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MilePerHour, new CultureInfo("en-US"), false, true, new string[]{"mph"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MilePerHour, new CultureInfo("ru-RU"), false, true, new string[]{"миль/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MillimeterPerHour, new CultureInfo("en-US"), false, true, new string[]{"mm/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MillimeterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"мм/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MillimeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"mm/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MillimeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"мм/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MillimeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.MillimeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мм/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.NanometerPerMinute, new CultureInfo("en-US"), false, true, new string[]{"nm/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.NanometerPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"нм/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.NanometerPerSecond, new CultureInfo("en-US"), false, true, new string[]{"nm/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.NanometerPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"нм/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.UsSurveyFootPerHour, new CultureInfo("en-US"), false, true, new string[]{"ftUS/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.UsSurveyFootPerMinute, new CultureInfo("en-US"), false, true, new string[]{"ftUS/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.UsSurveyFootPerSecond, new CultureInfo("en-US"), false, true, new string[]{"ftUS/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.YardPerHour, new CultureInfo("en-US"), false, true, new string[]{"yd/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.YardPerMinute, new CultureInfo("en-US"), false, true, new string[]{"yd/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(SpeedUnit.YardPerSecond, new CultureInfo("en-US"), false, true, new string[]{"yd/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(SpeedUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(SpeedUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.CentimeterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) + { + double value = (double) centimetersperhour; + return new Speed(value, SpeedUnit.CentimeterPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.CentimeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) + { + double value = (double) centimetersperminutes; + return new Speed(value, SpeedUnit.CentimeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.CentimeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) + { + double value = (double) centimeterspersecond; + return new Speed(value, SpeedUnit.CentimeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.DecimeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) + { + double value = (double) decimetersperminutes; + return new Speed(value, SpeedUnit.DecimeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.DecimeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) + { + double value = (double) decimeterspersecond; + return new Speed(value, SpeedUnit.DecimeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.FootPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromFeetPerHour(QuantityValue feetperhour) + { + double value = (double) feetperhour; + return new Speed(value, SpeedUnit.FootPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.FootPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromFeetPerMinute(QuantityValue feetperminute) + { + double value = (double) feetperminute; + return new Speed(value, SpeedUnit.FootPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.FootPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromFeetPerSecond(QuantityValue feetpersecond) + { + double value = (double) feetpersecond; + return new Speed(value, SpeedUnit.FootPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.InchPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromInchesPerHour(QuantityValue inchesperhour) + { + double value = (double) inchesperhour; + return new Speed(value, SpeedUnit.InchPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.InchPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromInchesPerMinute(QuantityValue inchesperminute) + { + double value = (double) inchesperminute; + return new Speed(value, SpeedUnit.InchPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.InchPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromInchesPerSecond(QuantityValue inchespersecond) + { + double value = (double) inchespersecond; + return new Speed(value, SpeedUnit.InchPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.KilometerPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) + { + double value = (double) kilometersperhour; + return new Speed(value, SpeedUnit.KilometerPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.KilometerPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) + { + double value = (double) kilometersperminutes; + return new Speed(value, SpeedUnit.KilometerPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.KilometerPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) + { + double value = (double) kilometerspersecond; + return new Speed(value, SpeedUnit.KilometerPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.Knot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromKnots(QuantityValue knots) + { + double value = (double) knots; + return new Speed(value, SpeedUnit.Knot); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.Mach"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMach(QuantityValue mach) + { + double value = (double) mach; + return new Speed(value, SpeedUnit.Mach); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MeterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMetersPerHour(QuantityValue metersperhour) + { + double value = (double) metersperhour; + return new Speed(value, SpeedUnit.MeterPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) + { + double value = (double) metersperminutes; + return new Speed(value, SpeedUnit.MeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMetersPerSecond(QuantityValue meterspersecond) + { + double value = (double) meterspersecond; + return new Speed(value, SpeedUnit.MeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MicrometerPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) + { + double value = (double) micrometersperminutes; + return new Speed(value, SpeedUnit.MicrometerPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MicrometerPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) + { + double value = (double) micrometerspersecond; + return new Speed(value, SpeedUnit.MicrometerPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MilePerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMilesPerHour(QuantityValue milesperhour) + { + double value = (double) milesperhour; + return new Speed(value, SpeedUnit.MilePerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MillimeterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) + { + double value = (double) millimetersperhour; + return new Speed(value, SpeedUnit.MillimeterPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MillimeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) + { + double value = (double) millimetersperminutes; + return new Speed(value, SpeedUnit.MillimeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.MillimeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) + { + double value = (double) millimeterspersecond; + return new Speed(value, SpeedUnit.MillimeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.NanometerPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) + { + double value = (double) nanometersperminutes; + return new Speed(value, SpeedUnit.NanometerPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.NanometerPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) + { + double value = (double) nanometerspersecond; + return new Speed(value, SpeedUnit.NanometerPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.UsSurveyFootPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) + { + double value = (double) ussurveyfeetperhour; + return new Speed(value, SpeedUnit.UsSurveyFootPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.UsSurveyFootPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) + { + double value = (double) ussurveyfeetperminute; + return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.UsSurveyFootPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) + { + double value = (double) ussurveyfeetpersecond; + return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.YardPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromYardsPerHour(QuantityValue yardsperhour) + { + double value = (double) yardsperhour; + return new Speed(value, SpeedUnit.YardPerHour); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.YardPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromYardsPerMinute(QuantityValue yardsperminute) + { + double value = (double) yardsperminute; + return new Speed(value, SpeedUnit.YardPerMinute); + } + + /// <summary> + /// Creates a <see cref="Speed"/> from <see cref="SpeedUnit.YardPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Speed FromYardsPerSecond(QuantityValue yardspersecond) + { + double value = (double) yardspersecond; + return new Speed(value, SpeedUnit.YardPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="SpeedUnit" /> to <see cref="Speed" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Speed unit value.</returns> + public static Speed From(QuantityValue value, SpeedUnit fromUnit) + { + return new Speed((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Speed Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Speed Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Speed, SpeedUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Speed result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Speed result) + { + return QuantityParser.Default.TryParse<Speed, SpeedUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpeedUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static SpeedUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<SpeedUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.SpeedUnit)"/> + public static bool TryParseUnit(string str, out SpeedUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out SpeedUnit unit) + { + return UnitParser.Default.TryParse<SpeedUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Speed operator -(Speed right) + { + return new Speed(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Speed"/> from adding two <see cref="Speed"/>.</summary> + public static Speed operator +(Speed left, Speed right) + { + return new Speed(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Speed"/> from subtracting two <see cref="Speed"/>.</summary> + public static Speed operator -(Speed left, Speed right) + { + return new Speed(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Speed"/> from multiplying value and <see cref="Speed"/>.</summary> + public static Speed operator *(double left, Speed right) + { + return new Speed(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Speed"/> from multiplying value and <see cref="Speed"/>.</summary> + public static Speed operator *(Speed left, double right) + { + return new Speed(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Speed"/> from dividing <see cref="Speed"/> by value.</summary> + public static Speed operator /(Speed left, double right) + { + return new Speed(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Speed"/> by <see cref="Speed"/>.</summary> + public static double operator /(Speed left, Speed right) + { + return left.MetersPerSecond / right.MetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Speed left, Speed right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Speed left, Speed right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Speed left, Speed right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Speed left, Speed right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Speed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Speed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Speed left, Speed right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Speed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Speed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Speed left, Speed right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Speed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Speed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Speed otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Speed"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Speed, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Speed other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Speed"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Speed otherQuantity)) throw new ArgumentException("Expected type Speed.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Speed"/> with another <see cref="Speed"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Speed other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Speed within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Speed.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(SpeedUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is SpeedUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Speed to another Speed with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Speed with the specified unit.</returns> + public Speed ToUnit(SpeedUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Speed"/> to another <see cref="Speed"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Speed with the specified unit.</returns> + public Speed ToUnit(SpeedUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Speed), Unit, typeof(Speed), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Speed)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Speed"/> to another <see cref="Speed"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Speed"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(SpeedUnit unit, [NotNullWhen(true)] out Speed? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Speed? convertedOrNull = (Unit, unit) switch + { + // SpeedUnit -> BaseUnit + (SpeedUnit.CentimeterPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 1e-2d, SpeedUnit.MeterPerSecond), + (SpeedUnit.CentimeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-2d, SpeedUnit.MeterPerSecond), + (SpeedUnit.CentimeterPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-2d, SpeedUnit.MeterPerSecond), + (SpeedUnit.DecimeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-1d, SpeedUnit.MeterPerSecond), + (SpeedUnit.DecimeterPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-1d, SpeedUnit.MeterPerSecond), + (SpeedUnit.FootPerHour, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.3048 / 3600, SpeedUnit.MeterPerSecond), + (SpeedUnit.FootPerMinute, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.3048 / 60, SpeedUnit.MeterPerSecond), + (SpeedUnit.FootPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.3048, SpeedUnit.MeterPerSecond), + (SpeedUnit.InchPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 2.54e-2, SpeedUnit.MeterPerSecond), + (SpeedUnit.InchPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 2.54e-2, SpeedUnit.MeterPerSecond), + (SpeedUnit.InchPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 2.54e-2, SpeedUnit.MeterPerSecond), + (SpeedUnit.KilometerPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 1e3d, SpeedUnit.MeterPerSecond), + (SpeedUnit.KilometerPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e3d, SpeedUnit.MeterPerSecond), + (SpeedUnit.KilometerPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e3d, SpeedUnit.MeterPerSecond), + (SpeedUnit.Knot, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.514444, SpeedUnit.MeterPerSecond), + (SpeedUnit.Mach, SpeedUnit.MeterPerSecond) => new Speed(_value * 340.29, SpeedUnit.MeterPerSecond), + (SpeedUnit.MeterPerHour, SpeedUnit.MeterPerSecond) => new Speed(_value / 3600, SpeedUnit.MeterPerSecond), + (SpeedUnit.MeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed(_value / 60, SpeedUnit.MeterPerSecond), + (SpeedUnit.MicrometerPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-6d, SpeedUnit.MeterPerSecond), + (SpeedUnit.MicrometerPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-6d, SpeedUnit.MeterPerSecond), + (SpeedUnit.MilePerHour, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.44704, SpeedUnit.MeterPerSecond), + (SpeedUnit.MillimeterPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 1e-3d, SpeedUnit.MeterPerSecond), + (SpeedUnit.MillimeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-3d, SpeedUnit.MeterPerSecond), + (SpeedUnit.MillimeterPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-3d, SpeedUnit.MeterPerSecond), + (SpeedUnit.NanometerPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-9d, SpeedUnit.MeterPerSecond), + (SpeedUnit.NanometerPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-9d, SpeedUnit.MeterPerSecond), + (SpeedUnit.UsSurveyFootPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value * 1200 / 3937) / 3600, SpeedUnit.MeterPerSecond), + (SpeedUnit.UsSurveyFootPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value * 1200 / 3937) / 60, SpeedUnit.MeterPerSecond), + (SpeedUnit.UsSurveyFootPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 1200 / 3937, SpeedUnit.MeterPerSecond), + (SpeedUnit.YardPerHour, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.9144 / 3600, SpeedUnit.MeterPerSecond), + (SpeedUnit.YardPerMinute, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.9144 / 60, SpeedUnit.MeterPerSecond), + (SpeedUnit.YardPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.9144, SpeedUnit.MeterPerSecond), + + // BaseUnit -> SpeedUnit + (SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerHour) => new Speed((_value * 3600) / 1e-2d, SpeedUnit.CentimeterPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerMinute) => new Speed((_value * 60) / 1e-2d, SpeedUnit.CentimeterPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerSecond) => new Speed((_value) / 1e-2d, SpeedUnit.CentimeterPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerMinute) => new Speed((_value * 60) / 1e-1d, SpeedUnit.DecimeterPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerSecond) => new Speed((_value) / 1e-1d, SpeedUnit.DecimeterPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.FootPerHour) => new Speed(_value / 0.3048 * 3600, SpeedUnit.FootPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.FootPerMinute) => new Speed(_value / 0.3048 * 60, SpeedUnit.FootPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.FootPerSecond) => new Speed(_value / 0.3048, SpeedUnit.FootPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.InchPerHour) => new Speed((_value / 2.54e-2) * 3600, SpeedUnit.InchPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.InchPerMinute) => new Speed((_value / 2.54e-2) * 60, SpeedUnit.InchPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.InchPerSecond) => new Speed(_value / 2.54e-2, SpeedUnit.InchPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerHour) => new Speed((_value * 3600) / 1e3d, SpeedUnit.KilometerPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerMinute) => new Speed((_value * 60) / 1e3d, SpeedUnit.KilometerPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerSecond) => new Speed((_value) / 1e3d, SpeedUnit.KilometerPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.Knot) => new Speed(_value / 0.514444, SpeedUnit.Knot), + (SpeedUnit.MeterPerSecond, SpeedUnit.Mach) => new Speed(_value / 340.29, SpeedUnit.Mach), + (SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerHour) => new Speed(_value * 3600, SpeedUnit.MeterPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerMinute) => new Speed(_value * 60, SpeedUnit.MeterPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerMinute) => new Speed((_value * 60) / 1e-6d, SpeedUnit.MicrometerPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerSecond) => new Speed((_value) / 1e-6d, SpeedUnit.MicrometerPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.MilePerHour) => new Speed(_value / 0.44704, SpeedUnit.MilePerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerHour) => new Speed((_value * 3600) / 1e-3d, SpeedUnit.MillimeterPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerMinute) => new Speed((_value * 60) / 1e-3d, SpeedUnit.MillimeterPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerSecond) => new Speed((_value) / 1e-3d, SpeedUnit.MillimeterPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerMinute) => new Speed((_value * 60) / 1e-9d, SpeedUnit.NanometerPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerSecond) => new Speed((_value) / 1e-9d, SpeedUnit.NanometerPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerHour) => new Speed((_value * 3937 / 1200) * 3600, SpeedUnit.UsSurveyFootPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerMinute) => new Speed((_value * 3937 / 1200) * 60, SpeedUnit.UsSurveyFootPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerSecond) => new Speed(_value * 3937 / 1200, SpeedUnit.UsSurveyFootPerSecond), + (SpeedUnit.MeterPerSecond, SpeedUnit.YardPerHour) => new Speed(_value / 0.9144 * 3600, SpeedUnit.YardPerHour), + (SpeedUnit.MeterPerSecond, SpeedUnit.YardPerMinute) => new Speed(_value / 0.9144 * 60, SpeedUnit.YardPerMinute), + (SpeedUnit.MeterPerSecond, SpeedUnit.YardPerSecond) => new Speed(_value / 0.9144, SpeedUnit.YardPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is SpeedUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<SpeedUnit> IQuantity<SpeedUnit>.ToUnit(SpeedUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<SpeedUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Speed)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Speed)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Speed)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Speed)) + return this; + else if (conversionType == typeof(SpeedUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Speed.Info; + else if (conversionType == typeof(BaseDimensions)) + return Speed.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Speed)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Speed/SpeedUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Speed/SpeedUnit.g.cs new file mode 100644 index 0000000000..4910d16b5d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Speed/SpeedUnit.g.cs @@ -0,0 +1,64 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum SpeedUnit + { + CentimeterPerHour = 1, + CentimeterPerMinute = 2, + CentimeterPerSecond = 3, + DecimeterPerMinute = 4, + DecimeterPerSecond = 5, + FootPerHour = 6, + FootPerMinute = 7, + FootPerSecond = 8, + InchPerHour = 9, + InchPerMinute = 10, + InchPerSecond = 11, + KilometerPerHour = 12, + KilometerPerMinute = 13, + KilometerPerSecond = 14, + Knot = 15, + Mach = 42, + MeterPerHour = 16, + MeterPerMinute = 17, + MeterPerSecond = 18, + MicrometerPerMinute = 19, + MicrometerPerSecond = 20, + MilePerHour = 21, + MillimeterPerHour = 22, + MillimeterPerMinute = 23, + MillimeterPerSecond = 24, + NanometerPerMinute = 25, + NanometerPerSecond = 26, + UsSurveyFootPerHour = 27, + UsSurveyFootPerMinute = 28, + UsSurveyFootPerSecond = 29, + YardPerHour = 30, + YardPerMinute = 31, + YardPerSecond = 32, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlow.csproj b/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlow.csproj new file mode 100644 index 0000000000..f528b9b468 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlow.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET StandardVolumeFlow</Title> + <Description>Adds StandardVolumeFlow units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>standardvolumeflow unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{5da7dbe9-f180-570f-2da0-2737f043744d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.StandardVolumeFlow</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlow.g.cs b/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlow.g.cs new file mode 100644 index 0000000000..1f498be3ba --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlow.g.cs @@ -0,0 +1,1006 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The molar flow rate of a gas corrected to standardized conditions of temperature and pressure thus representing a fixed number of moles of gas regardless of composition and actual flow conditions. + /// </summary> + [DataContract] + public readonly partial struct StandardVolumeFlow : IArithmeticQuantity<StandardVolumeFlow, StandardVolumeFlowUnit, double>, IEquatable<StandardVolumeFlow>, IComparable, IComparable<StandardVolumeFlow>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly StandardVolumeFlowUnit? _unit; + + static StandardVolumeFlow() + { + BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); + BaseUnit = StandardVolumeFlowUnit.StandardCubicMeterPerSecond; + Units = Enum.GetValues(typeof(StandardVolumeFlowUnit)).Cast<StandardVolumeFlowUnit>().ToArray(); + Zero = new StandardVolumeFlow(0, BaseUnit); + Info = new QuantityInfo<StandardVolumeFlowUnit>("StandardVolumeFlow", + new UnitInfo<StandardVolumeFlowUnit>[] + { + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, "StandardCubicCentimetersPerMinute", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicFootPerHour, "StandardCubicFeetPerHour", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicFootPerMinute, "StandardCubicFeetPerMinute", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicFootPerSecond, "StandardCubicFeetPerSecond", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicMeterPerDay, "StandardCubicMetersPerDay", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicMeterPerHour, "StandardCubicMetersPerHour", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, "StandardCubicMetersPerMinute", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, "StandardCubicMetersPerSecond", BaseUnits.Undefined), + new UnitInfo<StandardVolumeFlowUnit>(StandardVolumeFlowUnit.StandardLiterPerMinute, "StandardLitersPerMinute", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public StandardVolumeFlow(double value, StandardVolumeFlowUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="StandardVolumeFlow" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<StandardVolumeFlowUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of StandardVolumeFlow, which is StandardCubicMeterPerSecond. All conversions go via this value. + /// </summary> + public static StandardVolumeFlowUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the StandardVolumeFlow quantity. + /// </summary> + public static StandardVolumeFlowUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit StandardCubicMeterPerSecond. + /// </summary> + public static StandardVolumeFlow Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static StandardVolumeFlow AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public StandardVolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<StandardVolumeFlowUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => StandardVolumeFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute"/> + /// </summary> + public double StandardCubicCentimetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicFootPerHour"/> + /// </summary> + public double StandardCubicFeetPerHour => As(StandardVolumeFlowUnit.StandardCubicFootPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicFootPerMinute"/> + /// </summary> + public double StandardCubicFeetPerMinute => As(StandardVolumeFlowUnit.StandardCubicFootPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicFootPerSecond"/> + /// </summary> + public double StandardCubicFeetPerSecond => As(StandardVolumeFlowUnit.StandardCubicFootPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerDay"/> + /// </summary> + public double StandardCubicMetersPerDay => As(StandardVolumeFlowUnit.StandardCubicMeterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerHour"/> + /// </summary> + public double StandardCubicMetersPerHour => As(StandardVolumeFlowUnit.StandardCubicMeterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerMinute"/> + /// </summary> + public double StandardCubicMetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerSecond"/> + /// </summary> + public double StandardCubicMetersPerSecond => As(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="StandardVolumeFlowUnit.StandardLiterPerMinute"/> + /// </summary> + public double StandardLitersPerMinute => As(StandardVolumeFlowUnit.StandardLiterPerMinute); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: StandardVolumeFlowUnit -> BaseUnit + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicFootPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicFootPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicFootPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerDay, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardLiterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> StandardVolumeFlowUnit + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerHour, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerHour)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerMinute)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerSecond)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerDay, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerDay)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerHour, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerHour)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerMinute)); + unitConverter.SetConversionFunction<StandardVolumeFlow>(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardLiterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardLiterPerMinute)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"sccm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicFootPerHour, new CultureInfo("en-US"), false, true, new string[]{"scfh"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicFootPerMinute, new CultureInfo("en-US"), false, true, new string[]{"scfm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicFootPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Sft³/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicMeterPerDay, new CultureInfo("en-US"), false, true, new string[]{"Sm³/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicMeterPerHour, new CultureInfo("en-US"), false, true, new string[]{"Sm³/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"Sm³/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Sm³/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(StandardVolumeFlowUnit.StandardLiterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"slm"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(StandardVolumeFlowUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(StandardVolumeFlowUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(QuantityValue standardcubiccentimetersperminute) + { + double value = (double) standardcubiccentimetersperminute; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicFootPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicFeetPerHour(QuantityValue standardcubicfeetperhour) + { + double value = (double) standardcubicfeetperhour; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerHour); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicFootPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicFeetPerMinute(QuantityValue standardcubicfeetperminute) + { + double value = (double) standardcubicfeetperminute; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerMinute); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicFootPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicFeetPerSecond(QuantityValue standardcubicfeetpersecond) + { + double value = (double) standardcubicfeetpersecond; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerSecond); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicMetersPerDay(QuantityValue standardcubicmetersperday) + { + double value = (double) standardcubicmetersperday; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerDay); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicMetersPerHour(QuantityValue standardcubicmetersperhour) + { + double value = (double) standardcubicmetersperhour; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerHour); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicMetersPerMinute(QuantityValue standardcubicmetersperminute) + { + double value = (double) standardcubicmetersperminute; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardCubicMeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardCubicMetersPerSecond(QuantityValue standardcubicmeterspersecond) + { + double value = (double) standardcubicmeterspersecond; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="StandardVolumeFlow"/> from <see cref="StandardVolumeFlowUnit.StandardLiterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static StandardVolumeFlow FromStandardLitersPerMinute(QuantityValue standardlitersperminute) + { + double value = (double) standardlitersperminute; + return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardLiterPerMinute); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="StandardVolumeFlowUnit" /> to <see cref="StandardVolumeFlow" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>StandardVolumeFlow unit value.</returns> + public static StandardVolumeFlow From(QuantityValue value, StandardVolumeFlowUnit fromUnit) + { + return new StandardVolumeFlow((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static StandardVolumeFlow Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static StandardVolumeFlow Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<StandardVolumeFlow, StandardVolumeFlowUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out StandardVolumeFlow result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out StandardVolumeFlow result) + { + return QuantityParser.Default.TryParse<StandardVolumeFlow, StandardVolumeFlowUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static StandardVolumeFlowUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static StandardVolumeFlowUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<StandardVolumeFlowUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.StandardVolumeFlowUnit)"/> + public static bool TryParseUnit(string str, out StandardVolumeFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out StandardVolumeFlowUnit unit) + { + return UnitParser.Default.TryParse<StandardVolumeFlowUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static StandardVolumeFlow operator -(StandardVolumeFlow right) + { + return new StandardVolumeFlow(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="StandardVolumeFlow"/> from adding two <see cref="StandardVolumeFlow"/>.</summary> + public static StandardVolumeFlow operator +(StandardVolumeFlow left, StandardVolumeFlow right) + { + return new StandardVolumeFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="StandardVolumeFlow"/> from subtracting two <see cref="StandardVolumeFlow"/>.</summary> + public static StandardVolumeFlow operator -(StandardVolumeFlow left, StandardVolumeFlow right) + { + return new StandardVolumeFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="StandardVolumeFlow"/> from multiplying value and <see cref="StandardVolumeFlow"/>.</summary> + public static StandardVolumeFlow operator *(double left, StandardVolumeFlow right) + { + return new StandardVolumeFlow(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="StandardVolumeFlow"/> from multiplying value and <see cref="StandardVolumeFlow"/>.</summary> + public static StandardVolumeFlow operator *(StandardVolumeFlow left, double right) + { + return new StandardVolumeFlow(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="StandardVolumeFlow"/> from dividing <see cref="StandardVolumeFlow"/> by value.</summary> + public static StandardVolumeFlow operator /(StandardVolumeFlow left, double right) + { + return new StandardVolumeFlow(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="StandardVolumeFlow"/> by <see cref="StandardVolumeFlow"/>.</summary> + public static double operator /(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.StandardCubicMetersPerSecond / right.StandardCubicMetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="StandardVolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(StandardVolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(StandardVolumeFlow left, StandardVolumeFlow right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="StandardVolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(StandardVolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(StandardVolumeFlow left, StandardVolumeFlow right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="StandardVolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(StandardVolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is StandardVolumeFlow otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="StandardVolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(StandardVolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(StandardVolumeFlow other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="StandardVolumeFlow"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is StandardVolumeFlow otherQuantity)) throw new ArgumentException("Expected type StandardVolumeFlow.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="StandardVolumeFlow"/> with another <see cref="StandardVolumeFlow"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(StandardVolumeFlow other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another StandardVolumeFlow within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(StandardVolumeFlow other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current StandardVolumeFlow.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(StandardVolumeFlowUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is StandardVolumeFlowUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this StandardVolumeFlow to another StandardVolumeFlow with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A StandardVolumeFlow with the specified unit.</returns> + public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="StandardVolumeFlow"/> to another <see cref="StandardVolumeFlow"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A StandardVolumeFlow with the specified unit.</returns> + public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(StandardVolumeFlow), Unit, typeof(StandardVolumeFlow), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (StandardVolumeFlow)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="StandardVolumeFlow"/> to another <see cref="StandardVolumeFlow"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="StandardVolumeFlow"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(StandardVolumeFlowUnit unit, [NotNullWhen(true)] out StandardVolumeFlow? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + StandardVolumeFlow? convertedOrNull = (Unit, unit) switch + { + // StandardVolumeFlowUnit -> BaseUnit + (StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 6e7, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardCubicFootPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value * 7.8657907199999087346816086183876e-6, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardCubicFootPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 2118.88000326, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardCubicFootPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 35.314666721, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardCubicMeterPerDay, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 86400, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardCubicMeterPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 3600, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardCubicMeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 60, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + (StandardVolumeFlowUnit.StandardLiterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 60000, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), + + // BaseUnit -> StandardVolumeFlowUnit + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute) => new StandardVolumeFlow(_value * 6e7, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerHour) => new StandardVolumeFlow(_value / 7.8657907199999087346816086183876e-6, StandardVolumeFlowUnit.StandardCubicFootPerHour), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerMinute) => new StandardVolumeFlow(_value * 2118.88000326, StandardVolumeFlowUnit.StandardCubicFootPerMinute), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerSecond) => new StandardVolumeFlow(_value * 35.314666721, StandardVolumeFlowUnit.StandardCubicFootPerSecond), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerDay) => new StandardVolumeFlow(_value * 86400, StandardVolumeFlowUnit.StandardCubicMeterPerDay), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerHour) => new StandardVolumeFlow(_value * 3600, StandardVolumeFlowUnit.StandardCubicMeterPerHour), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerMinute) => new StandardVolumeFlow(_value * 60, StandardVolumeFlowUnit.StandardCubicMeterPerMinute), + (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardLiterPerMinute) => new StandardVolumeFlow(_value * 60000, StandardVolumeFlowUnit.StandardLiterPerMinute), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is StandardVolumeFlowUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<StandardVolumeFlowUnit> IQuantity<StandardVolumeFlowUnit>.ToUnit(StandardVolumeFlowUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<StandardVolumeFlowUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(StandardVolumeFlow)) + return this; + else if (conversionType == typeof(StandardVolumeFlowUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return StandardVolumeFlow.Info; + else if (conversionType == typeof(BaseDimensions)) + return StandardVolumeFlow.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlowUnit.g.cs b/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlowUnit.g.cs new file mode 100644 index 0000000000..212589934b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/StandardVolumeFlow/StandardVolumeFlowUnit.g.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum StandardVolumeFlowUnit + { + StandardCubicCentimeterPerMinute = 1, + StandardCubicFootPerHour = 2, + StandardCubicFootPerMinute = 3, + StandardCubicFootPerSecond = 4, + StandardCubicMeterPerDay = 5, + StandardCubicMeterPerHour = 6, + StandardCubicMeterPerMinute = 7, + StandardCubicMeterPerSecond = 8, + StandardLiterPerMinute = 9, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Temperature/Temperature.csproj b/UnitsNet.Modular/GeneratedCode/Temperature/Temperature.csproj new file mode 100644 index 0000000000..a718e71182 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Temperature/Temperature.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Temperature</Title> + <Description>Adds Temperature units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>temperature unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8bce58b9-1a87-6bb3-3cee-e0e0f012b618}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Temperature</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Temperature/Temperature.g.cs b/UnitsNet.Modular/GeneratedCode/Temperature/Temperature.g.cs new file mode 100644 index 0000000000..da05437134 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Temperature/Temperature.g.cs @@ -0,0 +1,978 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Temperature : IQuantity<Temperature, TemperatureUnit, double>, IEquatable<Temperature>, IComparable, IComparable<Temperature>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TemperatureUnit? _unit; + + static Temperature() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); + BaseUnit = TemperatureUnit.Kelvin; + Units = Enum.GetValues(typeof(TemperatureUnit)).Cast<TemperatureUnit>().ToArray(); + Zero = new Temperature(0, BaseUnit); + Info = new QuantityInfo<TemperatureUnit>("Temperature", + new UnitInfo<TemperatureUnit>[] + { + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeCelsius, "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeDelisle, "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeFahrenheit, "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeNewton, "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeRankine, "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeReaumur, "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.DegreeRoemer, "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.Kelvin, "Kelvins", new BaseUnits(temperature: TemperatureUnit.Kelvin)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.MillidegreeCelsius, "MillidegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)), + new UnitInfo<TemperatureUnit>(TemperatureUnit.SolarTemperature, "SolarTemperatures", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Temperature(double value, TemperatureUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Temperature" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TemperatureUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Temperature, which is Kelvin. All conversions go via this value. + /// </summary> + public static TemperatureUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Temperature quantity. + /// </summary> + public static TemperatureUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// </summary> + public static Temperature Zero { get; } + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TemperatureUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Temperature.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeCelsius"/> + /// </summary> + public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeDelisle"/> + /// </summary> + public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeFahrenheit"/> + /// </summary> + public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeNewton"/> + /// </summary> + public double DegreesNewton => As(TemperatureUnit.DegreeNewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeRankine"/> + /// </summary> + public double DegreesRankine => As(TemperatureUnit.DegreeRankine); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeReaumur"/> + /// </summary> + public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.DegreeRoemer"/> + /// </summary> + public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.Kelvin"/> + /// </summary> + public double Kelvins => As(TemperatureUnit.Kelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.MillidegreeCelsius"/> + /// </summary> + public double MillidegreesCelsius => As(TemperatureUnit.MillidegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureUnit.SolarTemperature"/> + /// </summary> + public double SolarTemperatures => As(TemperatureUnit.SolarTemperature); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TemperatureUnit -> BaseUnit + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeCelsius, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeDelisle, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeFahrenheit, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeNewton, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeRankine, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeReaumur, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.DegreeRoemer, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.MillidegreeCelsius, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.SolarTemperature, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.Kelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> TemperatureUnit + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeCelsius, quantity => quantity.ToUnit(TemperatureUnit.DegreeCelsius)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeDelisle, quantity => quantity.ToUnit(TemperatureUnit.DegreeDelisle)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeFahrenheit, quantity => quantity.ToUnit(TemperatureUnit.DegreeFahrenheit)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeNewton, quantity => quantity.ToUnit(TemperatureUnit.DegreeNewton)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRankine, quantity => quantity.ToUnit(TemperatureUnit.DegreeRankine)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeReaumur, quantity => quantity.ToUnit(TemperatureUnit.DegreeReaumur)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRoemer, quantity => quantity.ToUnit(TemperatureUnit.DegreeRoemer)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.MillidegreeCelsius, quantity => quantity.ToUnit(TemperatureUnit.MillidegreeCelsius)); + unitConverter.SetConversionFunction<Temperature>(TemperatureUnit.Kelvin, TemperatureUnit.SolarTemperature, quantity => quantity.ToUnit(TemperatureUnit.SolarTemperature)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeDelisle, new CultureInfo("en-US"), false, true, new string[]{"°De"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeNewton, new CultureInfo("en-US"), false, true, new string[]{"°N"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeRankine, new CultureInfo("en-US"), false, true, new string[]{"°R"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeReaumur, new CultureInfo("en-US"), false, true, new string[]{"°Ré"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.DegreeRoemer, new CultureInfo("en-US"), false, true, new string[]{"°Rø"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.Kelvin, new CultureInfo("en-US"), false, true, new string[]{"K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.MillidegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"m°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureUnit.SolarTemperature, new CultureInfo("en-US"), false, true, new string[]{"T⊙"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TemperatureUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TemperatureUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) + { + double value = (double) degreescelsius; + return new Temperature(value, TemperatureUnit.DegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeDelisle"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) + { + double value = (double) degreesdelisle; + return new Temperature(value, TemperatureUnit.DegreeDelisle); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new Temperature(value, TemperatureUnit.DegreeFahrenheit); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeNewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesNewton(QuantityValue degreesnewton) + { + double value = (double) degreesnewton; + return new Temperature(value, TemperatureUnit.DegreeNewton); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeRankine"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesRankine(QuantityValue degreesrankine) + { + double value = (double) degreesrankine; + return new Temperature(value, TemperatureUnit.DegreeRankine); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeReaumur"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) + { + double value = (double) degreesreaumur; + return new Temperature(value, TemperatureUnit.DegreeReaumur); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.DegreeRoemer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) + { + double value = (double) degreesroemer; + return new Temperature(value, TemperatureUnit.DegreeRoemer); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.Kelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromKelvins(QuantityValue kelvins) + { + double value = (double) kelvins; + return new Temperature(value, TemperatureUnit.Kelvin); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.MillidegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromMillidegreesCelsius(QuantityValue millidegreescelsius) + { + double value = (double) millidegreescelsius; + return new Temperature(value, TemperatureUnit.MillidegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="Temperature"/> from <see cref="TemperatureUnit.SolarTemperature"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Temperature FromSolarTemperatures(QuantityValue solartemperatures) + { + double value = (double) solartemperatures; + return new Temperature(value, TemperatureUnit.SolarTemperature); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TemperatureUnit" /> to <see cref="Temperature" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Temperature unit value.</returns> + public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) + { + return new Temperature((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Temperature Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Temperature Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Temperature, TemperatureUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Temperature result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Temperature result) + { + return QuantityParser.Default.TryParse<Temperature, TemperatureUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TemperatureUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TemperatureUnit)"/> + public static bool TryParseUnit(string str, out TemperatureUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureUnit unit) + { + return UnitParser.Default.TryParse<TemperatureUnit>(str, provider, out unit); + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Temperature left, Temperature right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Temperature left, Temperature right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Temperature left, Temperature right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Temperature left, Temperature right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Temperature"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Temperature, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Temperature left, Temperature right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Temperature"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Temperature, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Temperature left, Temperature right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Temperature"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Temperature, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Temperature otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Temperature"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Temperature, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Temperature other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Temperature"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Temperature otherQuantity)) throw new ArgumentException("Expected type Temperature.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Temperature"/> with another <see cref="Temperature"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Temperature other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Temperature within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Temperature.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TemperatureUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TemperatureUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Temperature to another Temperature with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Temperature with the specified unit.</returns> + public Temperature ToUnit(TemperatureUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Temperature"/> to another <see cref="Temperature"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Temperature with the specified unit.</returns> + public Temperature ToUnit(TemperatureUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Temperature), Unit, typeof(Temperature), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Temperature)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Temperature"/> to another <see cref="Temperature"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Temperature"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TemperatureUnit unit, [NotNullWhen(true)] out Temperature? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Temperature? convertedOrNull = (Unit, unit) switch + { + // TemperatureUnit -> BaseUnit + (TemperatureUnit.DegreeCelsius, TemperatureUnit.Kelvin) => new Temperature(_value + 273.15, TemperatureUnit.Kelvin), + (TemperatureUnit.DegreeDelisle, TemperatureUnit.Kelvin) => new Temperature(_value * -2 / 3 + 373.15, TemperatureUnit.Kelvin), + (TemperatureUnit.DegreeFahrenheit, TemperatureUnit.Kelvin) => new Temperature(_value * 5 / 9 + 459.67 * 5 / 9, TemperatureUnit.Kelvin), + (TemperatureUnit.DegreeNewton, TemperatureUnit.Kelvin) => new Temperature(_value * 100 / 33 + 273.15, TemperatureUnit.Kelvin), + (TemperatureUnit.DegreeRankine, TemperatureUnit.Kelvin) => new Temperature(_value * 5 / 9, TemperatureUnit.Kelvin), + (TemperatureUnit.DegreeReaumur, TemperatureUnit.Kelvin) => new Temperature(_value * 5 / 4 + 273.15, TemperatureUnit.Kelvin), + (TemperatureUnit.DegreeRoemer, TemperatureUnit.Kelvin) => new Temperature(_value * 40 / 21 + 273.15 - 7.5 * 40d / 21, TemperatureUnit.Kelvin), + (TemperatureUnit.MillidegreeCelsius, TemperatureUnit.Kelvin) => new Temperature(_value / 1000 + 273.15, TemperatureUnit.Kelvin), + (TemperatureUnit.SolarTemperature, TemperatureUnit.Kelvin) => new Temperature(_value * 5778, TemperatureUnit.Kelvin), + + // BaseUnit -> TemperatureUnit + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeCelsius) => new Temperature(_value - 273.15, TemperatureUnit.DegreeCelsius), + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeDelisle) => new Temperature((_value - 373.15) * -3 / 2, TemperatureUnit.DegreeDelisle), + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeFahrenheit) => new Temperature((_value - 459.67 * 5 / 9) * 9 / 5, TemperatureUnit.DegreeFahrenheit), + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeNewton) => new Temperature((_value - 273.15) * 33 / 100, TemperatureUnit.DegreeNewton), + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeRankine) => new Temperature(_value * 9 / 5, TemperatureUnit.DegreeRankine), + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeReaumur) => new Temperature((_value - 273.15) * 4 / 5, TemperatureUnit.DegreeReaumur), + (TemperatureUnit.Kelvin, TemperatureUnit.DegreeRoemer) => new Temperature((_value - (273.15 - 7.5 * 40d / 21)) * 21 / 40, TemperatureUnit.DegreeRoemer), + (TemperatureUnit.Kelvin, TemperatureUnit.MillidegreeCelsius) => new Temperature((_value - 273.15) * 1000, TemperatureUnit.MillidegreeCelsius), + (TemperatureUnit.Kelvin, TemperatureUnit.SolarTemperature) => new Temperature(_value / 5778, TemperatureUnit.SolarTemperature), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TemperatureUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TemperatureUnit> IQuantity<TemperatureUnit>.ToUnit(TemperatureUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TemperatureUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Temperature)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Temperature)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Temperature)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Temperature)) + return this; + else if (conversionType == typeof(TemperatureUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Temperature.Info; + else if (conversionType == typeof(BaseDimensions)) + return Temperature.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Temperature)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Temperature/TemperatureUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Temperature/TemperatureUnit.g.cs new file mode 100644 index 0000000000..51a02d8902 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Temperature/TemperatureUnit.g.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TemperatureUnit + { + DegreeCelsius = 1, + DegreeDelisle = 2, + DegreeFahrenheit = 3, + DegreeNewton = 4, + DegreeRankine = 5, + DegreeReaumur = 6, + DegreeRoemer = 7, + Kelvin = 8, + MillidegreeCelsius = 9, + SolarTemperature = 10, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRate.csproj b/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRate.csproj new file mode 100644 index 0000000000..70a49df4c5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRate.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET TemperatureChangeRate</Title> + <Description>Adds TemperatureChangeRate units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>temperaturechangerate unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{dfbb7b9f-c604-fedd-e658-17e196043123}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.TemperatureChangeRate</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRate.g.cs b/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRate.g.cs new file mode 100644 index 0000000000..ef35b2c052 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRate.g.cs @@ -0,0 +1,1027 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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). + /// </summary> + [DataContract] + public readonly partial struct TemperatureChangeRate : IArithmeticQuantity<TemperatureChangeRate, TemperatureChangeRateUnit, double>, IEquatable<TemperatureChangeRate>, IComparable, IComparable<TemperatureChangeRate>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TemperatureChangeRateUnit? _unit; + + static TemperatureChangeRate() + { + BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); + BaseUnit = TemperatureChangeRateUnit.DegreeCelsiusPerSecond; + Units = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast<TemperatureChangeRateUnit>().ToArray(); + Zero = new TemperatureChangeRate(0, BaseUnit); + Info = new QuantityInfo<TemperatureChangeRateUnit>("TemperatureChangeRate", + new UnitInfo<TemperatureChangeRateUnit>[] + { + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, "CentidegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, "DecadegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, "DecidegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, "DegreesCelsiusPerMinute", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, "DegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, "HectodegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, "KilodegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, "MicrodegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, "MillidegreesCelsiusPerSecond", BaseUnits.Undefined), + new UnitInfo<TemperatureChangeRateUnit>(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "NanodegreesCelsiusPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public TemperatureChangeRate(double value, TemperatureChangeRateUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="TemperatureChangeRate" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TemperatureChangeRateUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. + /// </summary> + public static TemperatureChangeRateUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the TemperatureChangeRate quantity. + /// </summary> + public static TemperatureChangeRateUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. + /// </summary> + public static TemperatureChangeRate Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static TemperatureChangeRate AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TemperatureChangeRateUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond"/> + /// </summary> + public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond"/> + /// </summary> + public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond"/> + /// </summary> + public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.DegreeCelsiusPerMinute"/> + /// </summary> + public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.DegreeCelsiusPerSecond"/> + /// </summary> + public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond"/> + /// </summary> + public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond"/> + /// </summary> + public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond"/> + /// </summary> + public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond"/> + /// </summary> + public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond"/> + /// </summary> + public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TemperatureChangeRateUnit -> BaseUnit + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> TemperatureChangeRateUnit + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerMinute, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerMinute)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond)); + unitConverter.SetConversionFunction<TemperatureChangeRate>(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"c°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"da°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"d°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, new CultureInfo("en-US"), false, true, new string[]{"°C/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"h°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"k°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µ°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"m°C/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, new CultureInfo("en-US"), false, true, new string[]{"n°C/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TemperatureChangeRateUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TemperatureChangeRateUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) + { + double value = (double) centidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) + { + double value = (double) decadegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) + { + double value = (double) decidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.DegreeCelsiusPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) + { + double value = (double) degreescelsiusperminute; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.DegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) + { + double value = (double) degreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) + { + double value = (double) hectodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) + { + double value = (double) kilodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) + { + double value = (double) microdegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) + { + double value = (double) millidegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + } + + /// <summary> + /// Creates a <see cref="TemperatureChangeRate"/> from <see cref="TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) + { + double value = (double) nanodegreescelsiuspersecond; + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TemperatureChangeRateUnit" /> to <see cref="TemperatureChangeRate" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>TemperatureChangeRate unit value.</returns> + public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) + { + return new TemperatureChangeRate((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static TemperatureChangeRate Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static TemperatureChangeRate Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<TemperatureChangeRate, TemperatureChangeRateUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out TemperatureChangeRate result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out TemperatureChangeRate result) + { + return QuantityParser.Default.TryParse<TemperatureChangeRate, TemperatureChangeRateUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureChangeRateUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TemperatureChangeRateUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TemperatureChangeRateUnit)"/> + public static bool TryParseUnit(string str, out TemperatureChangeRateUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureChangeRateUnit unit) + { + return UnitParser.Default.TryParse<TemperatureChangeRateUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static TemperatureChangeRate operator -(TemperatureChangeRate right) + { + return new TemperatureChangeRate(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="TemperatureChangeRate"/> from adding two <see cref="TemperatureChangeRate"/>.</summary> + public static TemperatureChangeRate operator +(TemperatureChangeRate left, TemperatureChangeRate right) + { + return new TemperatureChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TemperatureChangeRate"/> from subtracting two <see cref="TemperatureChangeRate"/>.</summary> + public static TemperatureChangeRate operator -(TemperatureChangeRate left, TemperatureChangeRate right) + { + return new TemperatureChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TemperatureChangeRate"/> from multiplying value and <see cref="TemperatureChangeRate"/>.</summary> + public static TemperatureChangeRate operator *(double left, TemperatureChangeRate right) + { + return new TemperatureChangeRate(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="TemperatureChangeRate"/> from multiplying value and <see cref="TemperatureChangeRate"/>.</summary> + public static TemperatureChangeRate operator *(TemperatureChangeRate left, double right) + { + return new TemperatureChangeRate(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="TemperatureChangeRate"/> from dividing <see cref="TemperatureChangeRate"/> by value.</summary> + public static TemperatureChangeRate operator /(TemperatureChangeRate left, double right) + { + return new TemperatureChangeRate(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="TemperatureChangeRate"/> by <see cref="TemperatureChangeRate"/>.</summary> + public static double operator /(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.DegreesCelsiusPerSecond / right.DegreesCelsiusPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="TemperatureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="TemperatureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TemperatureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is TemperatureChangeRate otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TemperatureChangeRate"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureChangeRate, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(TemperatureChangeRate other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="TemperatureChangeRate"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is TemperatureChangeRate otherQuantity)) throw new ArgumentException("Expected type TemperatureChangeRate.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="TemperatureChangeRate"/> with another <see cref="TemperatureChangeRate"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(TemperatureChangeRate other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another TemperatureChangeRate within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current TemperatureChangeRate.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TemperatureChangeRateUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TemperatureChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A TemperatureChangeRate with the specified unit.</returns> + public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="TemperatureChangeRate"/> to another <see cref="TemperatureChangeRate"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A TemperatureChangeRate with the specified unit.</returns> + public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(TemperatureChangeRate), Unit, typeof(TemperatureChangeRate), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (TemperatureChangeRate)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="TemperatureChangeRate"/> to another <see cref="TemperatureChangeRate"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="TemperatureChangeRate"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TemperatureChangeRateUnit unit, [NotNullWhen(true)] out TemperatureChangeRate? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + TemperatureChangeRate? convertedOrNull = (Unit, unit) switch + { + // TemperatureChangeRateUnit -> BaseUnit + (TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-2d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e1d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-1d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value / 60, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e2d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e3d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-6d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-3d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-9d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), + + // BaseUnit -> TemperatureChangeRateUnit + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-2d, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e1d, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-1d, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerMinute) => new TemperatureChangeRate(_value * 60, TemperatureChangeRateUnit.DegreeCelsiusPerMinute), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e2d, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e3d, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-6d, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-3d, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond), + (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-9d, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TemperatureChangeRateUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TemperatureChangeRateUnit> IQuantity<TemperatureChangeRateUnit>.ToUnit(TemperatureChangeRateUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TemperatureChangeRateUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(TemperatureChangeRate)) + return this; + else if (conversionType == typeof(TemperatureChangeRateUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return TemperatureChangeRate.Info; + else if (conversionType == typeof(BaseDimensions)) + return TemperatureChangeRate.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRateUnit.g.cs b/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRateUnit.g.cs new file mode 100644 index 0000000000..b06ed41185 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureChangeRate/TemperatureChangeRateUnit.g.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TemperatureChangeRateUnit + { + CentidegreeCelsiusPerSecond = 1, + DecadegreeCelsiusPerSecond = 2, + DecidegreeCelsiusPerSecond = 3, + DegreeCelsiusPerMinute = 4, + DegreeCelsiusPerSecond = 5, + HectodegreeCelsiusPerSecond = 6, + KilodegreeCelsiusPerSecond = 7, + MicrodegreeCelsiusPerSecond = 8, + MillidegreeCelsiusPerSecond = 9, + NanodegreeCelsiusPerSecond = 10, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDelta.csproj b/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDelta.csproj new file mode 100644 index 0000000000..f88c4a8abb --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDelta.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET TemperatureDelta</Title> + <Description>Adds TemperatureDelta units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>temperaturedelta unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8854c5e8-e40b-74c3-aafc-de0f13239276}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.TemperatureDelta</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDelta.g.cs b/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDelta.g.cs new file mode 100644 index 0000000000..535fbdb074 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDelta.g.cs @@ -0,0 +1,1006 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Difference between two temperatures. The conversions are different than for Temperature. + /// </summary> + [DataContract] + public readonly partial struct TemperatureDelta : IArithmeticQuantity<TemperatureDelta, TemperatureDeltaUnit, double>, IEquatable<TemperatureDelta>, IComparable, IComparable<TemperatureDelta>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TemperatureDeltaUnit? _unit; + + static TemperatureDelta() + { + BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); + BaseUnit = TemperatureDeltaUnit.Kelvin; + Units = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast<TemperatureDeltaUnit>().ToArray(); + Zero = new TemperatureDelta(0, BaseUnit); + Info = new QuantityInfo<TemperatureDeltaUnit>("TemperatureDelta", + new UnitInfo<TemperatureDeltaUnit>[] + { + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeCelsius, "DegreesCelsius", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeDelisle, "DegreesDelisle", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeFahrenheit, "DegreesFahrenheit", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeNewton, "DegreesNewton", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeRankine, "DegreesRankine", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeReaumur, "DegreesReaumur", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.DegreeRoemer, "DegreesRoemer", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.Kelvin, "Kelvins", BaseUnits.Undefined), + new UnitInfo<TemperatureDeltaUnit>(TemperatureDeltaUnit.MillidegreeCelsius, "MillidegreesCelsius", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public TemperatureDelta(double value, TemperatureDeltaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="TemperatureDelta" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TemperatureDeltaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. + /// </summary> + public static TemperatureDeltaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the TemperatureDelta quantity. + /// </summary> + public static TemperatureDeltaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. + /// </summary> + public static TemperatureDelta Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static TemperatureDelta AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TemperatureDeltaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeCelsius"/> + /// </summary> + public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeDelisle"/> + /// </summary> + public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeFahrenheit"/> + /// </summary> + public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeNewton"/> + /// </summary> + public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeRankine"/> + /// </summary> + public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeReaumur"/> + /// </summary> + public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.DegreeRoemer"/> + /// </summary> + public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.Kelvin"/> + /// </summary> + public double Kelvins => As(TemperatureDeltaUnit.Kelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureDeltaUnit.MillidegreeCelsius"/> + /// </summary> + public double MillidegreesCelsius => As(TemperatureDeltaUnit.MillidegreeCelsius); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TemperatureDeltaUnit -> BaseUnit + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeDelisle, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeFahrenheit, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeNewton, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeRankine, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeReaumur, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.DegreeRoemer, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.MillidegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.Kelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> TemperatureDeltaUnit + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeCelsius, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeCelsius)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeDelisle, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeDelisle)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeFahrenheit, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeFahrenheit)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeNewton, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeNewton)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRankine, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeRankine)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeReaumur, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeReaumur)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRoemer, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeRoemer)); + unitConverter.SetConversionFunction<TemperatureDelta>(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.MillidegreeCelsius, quantity => quantity.ToUnit(TemperatureDeltaUnit.MillidegreeCelsius)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"∆°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeDelisle, new CultureInfo("en-US"), false, true, new string[]{"∆°De"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"∆°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeNewton, new CultureInfo("en-US"), false, true, new string[]{"∆°N"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeRankine, new CultureInfo("en-US"), false, true, new string[]{"∆°R"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeReaumur, new CultureInfo("en-US"), false, true, new string[]{"∆°Ré"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.DegreeRoemer, new CultureInfo("en-US"), false, true, new string[]{"∆°Rø"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.Kelvin, new CultureInfo("en-US"), false, true, new string[]{"∆K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureDeltaUnit.MillidegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"∆m°C"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TemperatureDeltaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TemperatureDeltaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) + { + double value = (double) degreescelsius; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeDelisle"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) + { + double value = (double) degreesdelisle; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) + { + double value = (double) degreesfahrenheit; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeNewton"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) + { + double value = (double) degreesnewton; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeRankine"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) + { + double value = (double) degreesrankine; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeReaumur"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) + { + double value = (double) degreesreaumur; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.DegreeRoemer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) + { + double value = (double) degreesroemer; + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.Kelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromKelvins(QuantityValue kelvins) + { + double value = (double) kelvins; + return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); + } + + /// <summary> + /// Creates a <see cref="TemperatureDelta"/> from <see cref="TemperatureDeltaUnit.MillidegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureDelta FromMillidegreesCelsius(QuantityValue millidegreescelsius) + { + double value = (double) millidegreescelsius; + return new TemperatureDelta(value, TemperatureDeltaUnit.MillidegreeCelsius); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TemperatureDeltaUnit" /> to <see cref="TemperatureDelta" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>TemperatureDelta unit value.</returns> + public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) + { + return new TemperatureDelta((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static TemperatureDelta Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static TemperatureDelta Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<TemperatureDelta, TemperatureDeltaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out TemperatureDelta result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out TemperatureDelta result) + { + return QuantityParser.Default.TryParse<TemperatureDelta, TemperatureDeltaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureDeltaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TemperatureDeltaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TemperatureDeltaUnit)"/> + public static bool TryParseUnit(string str, out TemperatureDeltaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureDeltaUnit unit) + { + return UnitParser.Default.TryParse<TemperatureDeltaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static TemperatureDelta operator -(TemperatureDelta right) + { + return new TemperatureDelta(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="TemperatureDelta"/> from adding two <see cref="TemperatureDelta"/>.</summary> + public static TemperatureDelta operator +(TemperatureDelta left, TemperatureDelta right) + { + return new TemperatureDelta(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TemperatureDelta"/> from subtracting two <see cref="TemperatureDelta"/>.</summary> + public static TemperatureDelta operator -(TemperatureDelta left, TemperatureDelta right) + { + return new TemperatureDelta(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TemperatureDelta"/> from multiplying value and <see cref="TemperatureDelta"/>.</summary> + public static TemperatureDelta operator *(double left, TemperatureDelta right) + { + return new TemperatureDelta(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="TemperatureDelta"/> from multiplying value and <see cref="TemperatureDelta"/>.</summary> + public static TemperatureDelta operator *(TemperatureDelta left, double right) + { + return new TemperatureDelta(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="TemperatureDelta"/> from dividing <see cref="TemperatureDelta"/> by value.</summary> + public static TemperatureDelta operator /(TemperatureDelta left, double right) + { + return new TemperatureDelta(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="TemperatureDelta"/> by <see cref="TemperatureDelta"/>.</summary> + public static double operator /(TemperatureDelta left, TemperatureDelta right) + { + return left.Kelvins / right.Kelvins; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(TemperatureDelta left, TemperatureDelta right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(TemperatureDelta left, TemperatureDelta right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(TemperatureDelta left, TemperatureDelta right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(TemperatureDelta left, TemperatureDelta right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="TemperatureDelta"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureDelta, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(TemperatureDelta left, TemperatureDelta right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="TemperatureDelta"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureDelta, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(TemperatureDelta left, TemperatureDelta right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TemperatureDelta"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureDelta, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is TemperatureDelta otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TemperatureDelta"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureDelta, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(TemperatureDelta other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="TemperatureDelta"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is TemperatureDelta otherQuantity)) throw new ArgumentException("Expected type TemperatureDelta.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="TemperatureDelta"/> with another <see cref="TemperatureDelta"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(TemperatureDelta other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another TemperatureDelta within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current TemperatureDelta.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TemperatureDeltaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TemperatureDeltaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A TemperatureDelta with the specified unit.</returns> + public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="TemperatureDelta"/> to another <see cref="TemperatureDelta"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A TemperatureDelta with the specified unit.</returns> + public TemperatureDelta ToUnit(TemperatureDeltaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(TemperatureDelta), Unit, typeof(TemperatureDelta), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (TemperatureDelta)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="TemperatureDelta"/> to another <see cref="TemperatureDelta"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="TemperatureDelta"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TemperatureDeltaUnit unit, [NotNullWhen(true)] out TemperatureDelta? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + TemperatureDelta? convertedOrNull = (Unit, unit) switch + { + // TemperatureDeltaUnit -> BaseUnit + (TemperatureDeltaUnit.DegreeCelsius, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.DegreeDelisle, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * -2 / 3, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.DegreeFahrenheit, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 5 / 9, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.DegreeNewton, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 100 / 33, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.DegreeRankine, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 5 / 9, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.DegreeReaumur, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 5 / 4, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.DegreeRoemer, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 40 / 21, TemperatureDeltaUnit.Kelvin), + (TemperatureDeltaUnit.MillidegreeCelsius, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta((_value) * 1e-3d, TemperatureDeltaUnit.Kelvin), + + // BaseUnit -> TemperatureDeltaUnit + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeCelsius) => new TemperatureDelta(_value, TemperatureDeltaUnit.DegreeCelsius), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeDelisle) => new TemperatureDelta(_value * -3 / 2, TemperatureDeltaUnit.DegreeDelisle), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeFahrenheit) => new TemperatureDelta(_value * 9 / 5, TemperatureDeltaUnit.DegreeFahrenheit), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeNewton) => new TemperatureDelta(_value * 33 / 100, TemperatureDeltaUnit.DegreeNewton), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRankine) => new TemperatureDelta(_value * 9 / 5, TemperatureDeltaUnit.DegreeRankine), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeReaumur) => new TemperatureDelta(_value * 4 / 5, TemperatureDeltaUnit.DegreeReaumur), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRoemer) => new TemperatureDelta(_value * 21 / 40, TemperatureDeltaUnit.DegreeRoemer), + (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.MillidegreeCelsius) => new TemperatureDelta((_value) / 1e-3d, TemperatureDeltaUnit.MillidegreeCelsius), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TemperatureDeltaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TemperatureDeltaUnit> IQuantity<TemperatureDeltaUnit>.ToUnit(TemperatureDeltaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TemperatureDeltaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(TemperatureDelta)) + return this; + else if (conversionType == typeof(TemperatureDeltaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return TemperatureDelta.Info; + else if (conversionType == typeof(BaseDimensions)) + return TemperatureDelta.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDeltaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDeltaUnit.g.cs new file mode 100644 index 0000000000..7895e204a4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureDelta/TemperatureDeltaUnit.g.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TemperatureDeltaUnit + { + DegreeCelsius = 1, + DegreeDelisle = 2, + DegreeFahrenheit = 3, + DegreeNewton = 4, + DegreeRankine = 5, + DegreeReaumur = 6, + DegreeRoemer = 7, + Kelvin = 8, + MillidegreeCelsius = 9, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradient.csproj b/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradient.csproj new file mode 100644 index 0000000000..adf4cef6a1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradient.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET TemperatureGradient</Title> + <Description>Adds TemperatureGradient units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>temperaturegradient unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{83d1d75e-3c26-b8d0-f097-f99452e749cc}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.TemperatureGradient</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradient.g.cs b/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradient.g.cs new file mode 100644 index 0000000000..f03912434d --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradient.g.cs @@ -0,0 +1,901 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + [DataContract] + public readonly partial struct TemperatureGradient : IArithmeticQuantity<TemperatureGradient, TemperatureGradientUnit, double>, IEquatable<TemperatureGradient>, IComparable, IComparable<TemperatureGradient>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TemperatureGradientUnit? _unit; + + static TemperatureGradient() + { + BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); + BaseUnit = TemperatureGradientUnit.KelvinPerMeter; + Units = Enum.GetValues(typeof(TemperatureGradientUnit)).Cast<TemperatureGradientUnit>().ToArray(); + Zero = new TemperatureGradient(0, BaseUnit); + Info = new QuantityInfo<TemperatureGradientUnit>("TemperatureGradient", + new UnitInfo<TemperatureGradientUnit>[] + { + new UnitInfo<TemperatureGradientUnit>(TemperatureGradientUnit.DegreeCelsiusPerKilometer, "DegreesCelciusPerKilometer", new BaseUnits(length: LengthUnit.Kilometer, temperature: TemperatureUnit.DegreeCelsius)), + new UnitInfo<TemperatureGradientUnit>(TemperatureGradientUnit.DegreeCelsiusPerMeter, "DegreesCelciusPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.DegreeCelsius)), + new UnitInfo<TemperatureGradientUnit>(TemperatureGradientUnit.DegreeFahrenheitPerFoot, "DegreesFahrenheitPerFoot", new BaseUnits(length: LengthUnit.Foot, temperature: TemperatureUnit.DegreeFahrenheit)), + new UnitInfo<TemperatureGradientUnit>(TemperatureGradientUnit.KelvinPerMeter, "KelvinsPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.Kelvin)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public TemperatureGradient(double value, TemperatureGradientUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="TemperatureGradient" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TemperatureGradientUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of TemperatureGradient, which is KelvinPerMeter. All conversions go via this value. + /// </summary> + public static TemperatureGradientUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the TemperatureGradient quantity. + /// </summary> + public static TemperatureGradientUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit KelvinPerMeter. + /// </summary> + public static TemperatureGradient Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static TemperatureGradient AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TemperatureGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TemperatureGradientUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => TemperatureGradient.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureGradientUnit.DegreeCelsiusPerKilometer"/> + /// </summary> + public double DegreesCelciusPerKilometer => As(TemperatureGradientUnit.DegreeCelsiusPerKilometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureGradientUnit.DegreeCelsiusPerMeter"/> + /// </summary> + public double DegreesCelciusPerMeter => As(TemperatureGradientUnit.DegreeCelsiusPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureGradientUnit.DegreeFahrenheitPerFoot"/> + /// </summary> + public double DegreesFahrenheitPerFoot => As(TemperatureGradientUnit.DegreeFahrenheitPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TemperatureGradientUnit.KelvinPerMeter"/> + /// </summary> + public double KelvinsPerMeter => As(TemperatureGradientUnit.KelvinPerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TemperatureGradientUnit -> BaseUnit + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.DegreeCelsiusPerKilometer, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.KelvinPerMeter)); + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.DegreeCelsiusPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.KelvinPerMeter)); + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.DegreeFahrenheitPerFoot, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.KelvinPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> TemperatureGradientUnit + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerKilometer, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerKilometer)); + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerMeter)); + unitConverter.SetConversionFunction<TemperatureGradient>(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeFahrenheitPerFoot, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeFahrenheitPerFoot)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureGradientUnit.DegreeCelsiusPerKilometer, new CultureInfo("en-US"), false, true, new string[]{"∆°C/km"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureGradientUnit.DegreeCelsiusPerMeter, new CultureInfo("en-US"), false, true, new string[]{"∆°C/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureGradientUnit.DegreeFahrenheitPerFoot, new CultureInfo("en-US"), false, true, new string[]{"∆°F/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TemperatureGradientUnit.KelvinPerMeter, new CultureInfo("en-US"), false, true, new string[]{"∆°K/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TemperatureGradientUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TemperatureGradientUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="TemperatureGradient"/> from <see cref="TemperatureGradientUnit.DegreeCelsiusPerKilometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureGradient FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) + { + double value = (double) degreescelciusperkilometer; + return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerKilometer); + } + + /// <summary> + /// Creates a <see cref="TemperatureGradient"/> from <see cref="TemperatureGradientUnit.DegreeCelsiusPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureGradient FromDegreesCelciusPerMeter(QuantityValue degreescelciuspermeter) + { + double value = (double) degreescelciuspermeter; + return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerMeter); + } + + /// <summary> + /// Creates a <see cref="TemperatureGradient"/> from <see cref="TemperatureGradientUnit.DegreeFahrenheitPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureGradient FromDegreesFahrenheitPerFoot(QuantityValue degreesfahrenheitperfoot) + { + double value = (double) degreesfahrenheitperfoot; + return new TemperatureGradient(value, TemperatureGradientUnit.DegreeFahrenheitPerFoot); + } + + /// <summary> + /// Creates a <see cref="TemperatureGradient"/> from <see cref="TemperatureGradientUnit.KelvinPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TemperatureGradient FromKelvinsPerMeter(QuantityValue kelvinspermeter) + { + double value = (double) kelvinspermeter; + return new TemperatureGradient(value, TemperatureGradientUnit.KelvinPerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TemperatureGradientUnit" /> to <see cref="TemperatureGradient" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>TemperatureGradient unit value.</returns> + public static TemperatureGradient From(QuantityValue value, TemperatureGradientUnit fromUnit) + { + return new TemperatureGradient((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static TemperatureGradient Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static TemperatureGradient Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<TemperatureGradient, TemperatureGradientUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out TemperatureGradient result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out TemperatureGradient result) + { + return QuantityParser.Default.TryParse<TemperatureGradient, TemperatureGradientUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureGradientUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TemperatureGradientUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TemperatureGradientUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TemperatureGradientUnit)"/> + public static bool TryParseUnit(string str, out TemperatureGradientUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TemperatureGradientUnit unit) + { + return UnitParser.Default.TryParse<TemperatureGradientUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static TemperatureGradient operator -(TemperatureGradient right) + { + return new TemperatureGradient(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="TemperatureGradient"/> from adding two <see cref="TemperatureGradient"/>.</summary> + public static TemperatureGradient operator +(TemperatureGradient left, TemperatureGradient right) + { + return new TemperatureGradient(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TemperatureGradient"/> from subtracting two <see cref="TemperatureGradient"/>.</summary> + public static TemperatureGradient operator -(TemperatureGradient left, TemperatureGradient right) + { + return new TemperatureGradient(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TemperatureGradient"/> from multiplying value and <see cref="TemperatureGradient"/>.</summary> + public static TemperatureGradient operator *(double left, TemperatureGradient right) + { + return new TemperatureGradient(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="TemperatureGradient"/> from multiplying value and <see cref="TemperatureGradient"/>.</summary> + public static TemperatureGradient operator *(TemperatureGradient left, double right) + { + return new TemperatureGradient(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="TemperatureGradient"/> from dividing <see cref="TemperatureGradient"/> by value.</summary> + public static TemperatureGradient operator /(TemperatureGradient left, double right) + { + return new TemperatureGradient(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="TemperatureGradient"/> by <see cref="TemperatureGradient"/>.</summary> + public static double operator /(TemperatureGradient left, TemperatureGradient right) + { + return left.KelvinsPerMeter / right.KelvinsPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(TemperatureGradient left, TemperatureGradient right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(TemperatureGradient left, TemperatureGradient right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(TemperatureGradient left, TemperatureGradient right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(TemperatureGradient left, TemperatureGradient right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="TemperatureGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(TemperatureGradient left, TemperatureGradient right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="TemperatureGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(TemperatureGradient left, TemperatureGradient right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TemperatureGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is TemperatureGradient otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TemperatureGradient"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TemperatureGradient, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(TemperatureGradient other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="TemperatureGradient"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is TemperatureGradient otherQuantity)) throw new ArgumentException("Expected type TemperatureGradient.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="TemperatureGradient"/> with another <see cref="TemperatureGradient"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(TemperatureGradient other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another TemperatureGradient within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(TemperatureGradient other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current TemperatureGradient.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TemperatureGradientUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TemperatureGradientUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this TemperatureGradient to another TemperatureGradient with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A TemperatureGradient with the specified unit.</returns> + public TemperatureGradient ToUnit(TemperatureGradientUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="TemperatureGradient"/> to another <see cref="TemperatureGradient"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A TemperatureGradient with the specified unit.</returns> + public TemperatureGradient ToUnit(TemperatureGradientUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(TemperatureGradient), Unit, typeof(TemperatureGradient), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (TemperatureGradient)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="TemperatureGradient"/> to another <see cref="TemperatureGradient"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="TemperatureGradient"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TemperatureGradientUnit unit, [NotNullWhen(true)] out TemperatureGradient? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + TemperatureGradient? convertedOrNull = (Unit, unit) switch + { + // TemperatureGradientUnit -> BaseUnit + (TemperatureGradientUnit.DegreeCelsiusPerKilometer, TemperatureGradientUnit.KelvinPerMeter) => new TemperatureGradient(_value / 1e3, TemperatureGradientUnit.KelvinPerMeter), + (TemperatureGradientUnit.DegreeCelsiusPerMeter, TemperatureGradientUnit.KelvinPerMeter) => new TemperatureGradient(_value, TemperatureGradientUnit.KelvinPerMeter), + (TemperatureGradientUnit.DegreeFahrenheitPerFoot, TemperatureGradientUnit.KelvinPerMeter) => new TemperatureGradient((_value / 0.3048) * 5 / 9, TemperatureGradientUnit.KelvinPerMeter), + + // BaseUnit -> TemperatureGradientUnit + (TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerKilometer) => new TemperatureGradient(_value * 1e3, TemperatureGradientUnit.DegreeCelsiusPerKilometer), + (TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerMeter) => new TemperatureGradient(_value, TemperatureGradientUnit.DegreeCelsiusPerMeter), + (TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeFahrenheitPerFoot) => new TemperatureGradient((_value * 0.3048) * 9 / 5, TemperatureGradientUnit.DegreeFahrenheitPerFoot), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TemperatureGradientUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TemperatureGradientUnit> IQuantity<TemperatureGradientUnit>.ToUnit(TemperatureGradientUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TemperatureGradientUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(TemperatureGradient)) + return this; + else if (conversionType == typeof(TemperatureGradientUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return TemperatureGradient.Info; + else if (conversionType == typeof(BaseDimensions)) + return TemperatureGradient.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradientUnit.g.cs b/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradientUnit.g.cs new file mode 100644 index 0000000000..73040b84a2 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TemperatureGradient/TemperatureGradientUnit.g.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TemperatureGradientUnit + { + DegreeCelsiusPerKilometer = 1, + DegreeCelsiusPerMeter = 2, + DegreeFahrenheitPerFoot = 3, + KelvinPerMeter = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivity.csproj b/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivity.csproj new file mode 100644 index 0000000000..db86b22f57 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ThermalConductivity</Title> + <Description>Adds ThermalConductivity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>thermalconductivity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{7e7d8010-b37a-151a-11a5-1db234ee1104}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ThermalConductivity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivity.g.cs b/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivity.g.cs new file mode 100644 index 0000000000..4edba449f4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivity.g.cs @@ -0,0 +1,862 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Thermal conductivity is the property of a material to conduct heat. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Thermal_Conductivity + /// </remarks> + [DataContract] + public readonly partial struct ThermalConductivity : IArithmeticQuantity<ThermalConductivity, ThermalConductivityUnit, double>, IEquatable<ThermalConductivity>, IComparable, IComparable<ThermalConductivity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ThermalConductivityUnit? _unit; + + static ThermalConductivity() + { + BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); + BaseUnit = ThermalConductivityUnit.WattPerMeterKelvin; + Units = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast<ThermalConductivityUnit>().ToArray(); + Zero = new ThermalConductivity(0, BaseUnit); + Info = new QuantityInfo<ThermalConductivityUnit>("ThermalConductivity", + new UnitInfo<ThermalConductivityUnit>[] + { + new UnitInfo<ThermalConductivityUnit>(ThermalConductivityUnit.BtuPerHourFootFahrenheit, "BtusPerHourFootFahrenheit", BaseUnits.Undefined), + new UnitInfo<ThermalConductivityUnit>(ThermalConductivityUnit.WattPerMeterKelvin, "WattsPerMeterKelvin", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ThermalConductivity(double value, ThermalConductivityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ThermalConductivity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ThermalConductivityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. + /// </summary> + public static ThermalConductivityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ThermalConductivity quantity. + /// </summary> + public static ThermalConductivityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. + /// </summary> + public static ThermalConductivity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ThermalConductivity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ThermalConductivityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalConductivityUnit.BtuPerHourFootFahrenheit"/> + /// </summary> + public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalConductivityUnit.WattPerMeterKelvin"/> + /// </summary> + public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ThermalConductivityUnit -> BaseUnit + unitConverter.SetConversionFunction<ThermalConductivity>(ThermalConductivityUnit.BtuPerHourFootFahrenheit, ThermalConductivityUnit.WattPerMeterKelvin, quantity => quantity.ToUnit(ThermalConductivityUnit.WattPerMeterKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ThermalConductivity>(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.WattPerMeterKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> ThermalConductivityUnit + unitConverter.SetConversionFunction<ThermalConductivity>(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.BtuPerHourFootFahrenheit, quantity => quantity.ToUnit(ThermalConductivityUnit.BtuPerHourFootFahrenheit)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalConductivityUnit.BtuPerHourFootFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"BTU/h·ft·°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalConductivityUnit.WattPerMeterKelvin, new CultureInfo("en-US"), false, true, new string[]{"W/m·K"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ThermalConductivityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ThermalConductivityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ThermalConductivity"/> from <see cref="ThermalConductivityUnit.BtuPerHourFootFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue btusperhourfootfahrenheit) + { + double value = (double) btusperhourfootfahrenheit; + return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); + } + + /// <summary> + /// Creates a <see cref="ThermalConductivity"/> from <see cref="ThermalConductivityUnit.WattPerMeterKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) + { + double value = (double) wattspermeterkelvin; + return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ThermalConductivityUnit" /> to <see cref="ThermalConductivity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ThermalConductivity unit value.</returns> + public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) + { + return new ThermalConductivity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ThermalConductivity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ThermalConductivity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ThermalConductivity, ThermalConductivityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ThermalConductivity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ThermalConductivity result) + { + return QuantityParser.Default.TryParse<ThermalConductivity, ThermalConductivityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ThermalConductivityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ThermalConductivityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ThermalConductivityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ThermalConductivityUnit)"/> + public static bool TryParseUnit(string str, out ThermalConductivityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ThermalConductivityUnit unit) + { + return UnitParser.Default.TryParse<ThermalConductivityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ThermalConductivity operator -(ThermalConductivity right) + { + return new ThermalConductivity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ThermalConductivity"/> from adding two <see cref="ThermalConductivity"/>.</summary> + public static ThermalConductivity operator +(ThermalConductivity left, ThermalConductivity right) + { + return new ThermalConductivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ThermalConductivity"/> from subtracting two <see cref="ThermalConductivity"/>.</summary> + public static ThermalConductivity operator -(ThermalConductivity left, ThermalConductivity right) + { + return new ThermalConductivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ThermalConductivity"/> from multiplying value and <see cref="ThermalConductivity"/>.</summary> + public static ThermalConductivity operator *(double left, ThermalConductivity right) + { + return new ThermalConductivity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ThermalConductivity"/> from multiplying value and <see cref="ThermalConductivity"/>.</summary> + public static ThermalConductivity operator *(ThermalConductivity left, double right) + { + return new ThermalConductivity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ThermalConductivity"/> from dividing <see cref="ThermalConductivity"/> by value.</summary> + public static ThermalConductivity operator /(ThermalConductivity left, double right) + { + return new ThermalConductivity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ThermalConductivity"/> by <see cref="ThermalConductivity"/>.</summary> + public static double operator /(ThermalConductivity left, ThermalConductivity right) + { + return left.WattsPerMeterKelvin / right.WattsPerMeterKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ThermalConductivity left, ThermalConductivity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ThermalConductivity left, ThermalConductivity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ThermalConductivity left, ThermalConductivity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ThermalConductivity left, ThermalConductivity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ThermalConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ThermalConductivity left, ThermalConductivity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ThermalConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ThermalConductivity left, ThermalConductivity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ThermalConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ThermalConductivity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ThermalConductivity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalConductivity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ThermalConductivity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ThermalConductivity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ThermalConductivity otherQuantity)) throw new ArgumentException("Expected type ThermalConductivity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ThermalConductivity"/> with another <see cref="ThermalConductivity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ThermalConductivity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ThermalConductivity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ThermalConductivity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ThermalConductivityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ThermalConductivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ThermalConductivity with the specified unit.</returns> + public ThermalConductivity ToUnit(ThermalConductivityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ThermalConductivity"/> to another <see cref="ThermalConductivity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ThermalConductivity with the specified unit.</returns> + public ThermalConductivity ToUnit(ThermalConductivityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ThermalConductivity), Unit, typeof(ThermalConductivity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ThermalConductivity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ThermalConductivity"/> to another <see cref="ThermalConductivity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ThermalConductivity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ThermalConductivityUnit unit, [NotNullWhen(true)] out ThermalConductivity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ThermalConductivity? convertedOrNull = (Unit, unit) switch + { + // ThermalConductivityUnit -> BaseUnit + (ThermalConductivityUnit.BtuPerHourFootFahrenheit, ThermalConductivityUnit.WattPerMeterKelvin) => new ThermalConductivity(_value * 1.73073467, ThermalConductivityUnit.WattPerMeterKelvin), + + // BaseUnit -> ThermalConductivityUnit + (ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.BtuPerHourFootFahrenheit) => new ThermalConductivity(_value / 1.73073467, ThermalConductivityUnit.BtuPerHourFootFahrenheit), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ThermalConductivityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ThermalConductivityUnit> IQuantity<ThermalConductivityUnit>.ToUnit(ThermalConductivityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ThermalConductivityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ThermalConductivity)) + return this; + else if (conversionType == typeof(ThermalConductivityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ThermalConductivity.Info; + else if (conversionType == typeof(BaseDimensions)) + return ThermalConductivity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivityUnit.g.cs new file mode 100644 index 0000000000..044fda144e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ThermalConductivity/ThermalConductivityUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ThermalConductivityUnit + { + BtuPerHourFootFahrenheit = 1, + WattPerMeterKelvin = 2, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistance.csproj b/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistance.csproj new file mode 100644 index 0000000000..8b833dfcaf --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistance.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET ThermalResistance</Title> + <Description>Adds ThermalResistance units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>thermalresistance unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c69bdd4d-3ebd-4b8e-cffb-650903da3872}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.ThermalResistance</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistance.g.cs b/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistance.g.cs new file mode 100644 index 0000000000..ea919d0c73 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistance.g.cs @@ -0,0 +1,943 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Heat Transfer Coefficient or Thermal conductivity - indicates a materials ability to conduct heat. + /// </summary> + [DataContract] + public readonly partial struct ThermalResistance : IArithmeticQuantity<ThermalResistance, ThermalResistanceUnit, double>, IEquatable<ThermalResistance>, IComparable, IComparable<ThermalResistance>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly ThermalResistanceUnit? _unit; + + static ThermalResistance() + { + BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); + BaseUnit = ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; + Units = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast<ThermalResistanceUnit>().ToArray(); + Zero = new ThermalResistance(0, BaseUnit); + Info = new QuantityInfo<ThermalResistanceUnit>("ThermalResistance", + new UnitInfo<ThermalResistanceUnit>[] + { + new UnitInfo<ThermalResistanceUnit>(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, "HourSquareFeetDegreesFahrenheitPerBtu", BaseUnits.Undefined), + new UnitInfo<ThermalResistanceUnit>(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, "SquareCentimeterHourDegreesCelsiusPerKilocalorie", BaseUnits.Undefined), + new UnitInfo<ThermalResistanceUnit>(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, "SquareCentimeterKelvinsPerWatt", BaseUnits.Undefined), + new UnitInfo<ThermalResistanceUnit>(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, "SquareMeterDegreesCelsiusPerWatt", BaseUnits.Undefined), + new UnitInfo<ThermalResistanceUnit>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, "SquareMeterKelvinsPerKilowatt", BaseUnits.Undefined), + new UnitInfo<ThermalResistanceUnit>(ThermalResistanceUnit.SquareMeterKelvinPerWatt, "SquareMeterKelvinsPerWatt", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public ThermalResistance(double value, ThermalResistanceUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="ThermalResistance" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<ThermalResistanceUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of ThermalResistance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. + /// </summary> + public static ThermalResistanceUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the ThermalResistance quantity. + /// </summary> + public static ThermalResistanceUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. + /// </summary> + public static ThermalResistance Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static ThermalResistance AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<ThermalResistanceUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => ThermalResistance.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu"/> + /// </summary> + public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie"/> + /// </summary> + public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalResistanceUnit.SquareCentimeterKelvinPerWatt"/> + /// </summary> + public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt"/> + /// </summary> + public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalResistanceUnit.SquareMeterKelvinPerKilowatt"/> + /// </summary> + public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="ThermalResistanceUnit.SquareMeterKelvinPerWatt"/> + /// </summary> + public double SquareMeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareMeterKelvinPerWatt); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: ThermalResistanceUnit -> BaseUnit + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity); + + // Register in unit converter: BaseUnit -> ThermalResistanceUnit + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, quantity => quantity.ToUnit(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt)); + unitConverter.SetConversionFunction<ThermalResistance>(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.SquareMeterKelvinPerWatt)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, new CultureInfo("en-US"), false, true, new string[]{"Hrft²°F/Btu"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, new CultureInfo("en-US"), false, true, new string[]{"cm²Hr°C/kcal"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, new CultureInfo("en-US"), false, true, new string[]{"cm²K/W"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, new CultureInfo("en-US"), false, true, new string[]{"m²°C/W"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, new CultureInfo("en-US"), false, true, new string[]{"m²K/kW"}); + unitAbbreviationsCache.PerformAbbreviationMapping(ThermalResistanceUnit.SquareMeterKelvinPerWatt, new CultureInfo("en-US"), false, true, new string[]{"m²K/W"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(ThermalResistanceUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(ThermalResistanceUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="ThermalResistance"/> from <see cref="ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) + { + double value = (double) hoursquarefeetdegreesfahrenheitperbtu; + return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + } + + /// <summary> + /// Creates a <see cref="ThermalResistance"/> from <see cref="ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) + { + double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + } + + /// <summary> + /// Creates a <see cref="ThermalResistance"/> from <see cref="ThermalResistanceUnit.SquareCentimeterKelvinPerWatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) + { + double value = (double) squarecentimeterkelvinsperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); + } + + /// <summary> + /// Creates a <see cref="ThermalResistance"/> from <see cref="ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) + { + double value = (double) squaremeterdegreescelsiusperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); + } + + /// <summary> + /// Creates a <see cref="ThermalResistance"/> from <see cref="ThermalResistanceUnit.SquareMeterKelvinPerKilowatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) + { + double value = (double) squaremeterkelvinsperkilowatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); + } + + /// <summary> + /// Creates a <see cref="ThermalResistance"/> from <see cref="ThermalResistanceUnit.SquareMeterKelvinPerWatt"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static ThermalResistance FromSquareMeterKelvinsPerWatt(QuantityValue squaremeterkelvinsperwatt) + { + double value = (double) squaremeterkelvinsperwatt; + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerWatt); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="ThermalResistanceUnit" /> to <see cref="ThermalResistance" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>ThermalResistance unit value.</returns> + public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) + { + return new ThermalResistance((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static ThermalResistance Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static ThermalResistance Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<ThermalResistance, ThermalResistanceUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out ThermalResistance result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out ThermalResistance result) + { + return QuantityParser.Default.TryParse<ThermalResistance, ThermalResistanceUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ThermalResistanceUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static ThermalResistanceUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<ThermalResistanceUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ThermalResistanceUnit)"/> + public static bool TryParseUnit(string str, out ThermalResistanceUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out ThermalResistanceUnit unit) + { + return UnitParser.Default.TryParse<ThermalResistanceUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static ThermalResistance operator -(ThermalResistance right) + { + return new ThermalResistance(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="ThermalResistance"/> from adding two <see cref="ThermalResistance"/>.</summary> + public static ThermalResistance operator +(ThermalResistance left, ThermalResistance right) + { + return new ThermalResistance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ThermalResistance"/> from subtracting two <see cref="ThermalResistance"/>.</summary> + public static ThermalResistance operator -(ThermalResistance left, ThermalResistance right) + { + return new ThermalResistance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="ThermalResistance"/> from multiplying value and <see cref="ThermalResistance"/>.</summary> + public static ThermalResistance operator *(double left, ThermalResistance right) + { + return new ThermalResistance(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="ThermalResistance"/> from multiplying value and <see cref="ThermalResistance"/>.</summary> + public static ThermalResistance operator *(ThermalResistance left, double right) + { + return new ThermalResistance(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="ThermalResistance"/> from dividing <see cref="ThermalResistance"/> by value.</summary> + public static ThermalResistance operator /(ThermalResistance left, double right) + { + return new ThermalResistance(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="ThermalResistance"/> by <see cref="ThermalResistance"/>.</summary> + public static double operator /(ThermalResistance left, ThermalResistance right) + { + return left.SquareMeterKelvinsPerKilowatt / right.SquareMeterKelvinsPerKilowatt; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(ThermalResistance left, ThermalResistance right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(ThermalResistance left, ThermalResistance right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(ThermalResistance left, ThermalResistance right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(ThermalResistance left, ThermalResistance right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="ThermalResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(ThermalResistance left, ThermalResistance right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="ThermalResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(ThermalResistance left, ThermalResistance right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ThermalResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is ThermalResistance otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="ThermalResistance"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(ThermalResistance, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(ThermalResistance other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="ThermalResistance"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is ThermalResistance otherQuantity)) throw new ArgumentException("Expected type ThermalResistance.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="ThermalResistance"/> with another <see cref="ThermalResistance"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(ThermalResistance other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another ThermalResistance within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current ThermalResistance.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(ThermalResistanceUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is ThermalResistanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this ThermalResistance to another ThermalResistance with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A ThermalResistance with the specified unit.</returns> + public ThermalResistance ToUnit(ThermalResistanceUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="ThermalResistance"/> to another <see cref="ThermalResistance"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A ThermalResistance with the specified unit.</returns> + public ThermalResistance ToUnit(ThermalResistanceUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(ThermalResistance), Unit, typeof(ThermalResistance), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (ThermalResistance)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="ThermalResistance"/> to another <see cref="ThermalResistance"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="ThermalResistance"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(ThermalResistanceUnit unit, [NotNullWhen(true)] out ThermalResistance? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + ThermalResistance? convertedOrNull = (Unit, unit) switch + { + // ThermalResistanceUnit -> BaseUnit + (ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalResistance(_value * 176.1121482159839, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt), + (ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalResistance(_value * 0.0859779507590433, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt), + (ThermalResistanceUnit.SquareCentimeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalResistance(_value * 0.1, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt), + (ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalResistance(_value * 1000.0, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt), + (ThermalResistanceUnit.SquareMeterKelvinPerWatt, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalResistance(_value * 1000, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt), + + // BaseUnit -> ThermalResistanceUnit + (ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu) => new ThermalResistance(_value / 176.1121482159839, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu), + (ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie) => new ThermalResistance(_value / 0.0859779507590433, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie), + (ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt) => new ThermalResistance(_value / 0.1, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt), + (ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt) => new ThermalResistance(_value / 1000.0, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt), + (ThermalResistanceUnit.SquareMeterKelvinPerKilowatt, ThermalResistanceUnit.SquareMeterKelvinPerWatt) => new ThermalResistance(_value / 1000, ThermalResistanceUnit.SquareMeterKelvinPerWatt), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is ThermalResistanceUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<ThermalResistanceUnit> IQuantity<ThermalResistanceUnit>.ToUnit(ThermalResistanceUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<ThermalResistanceUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ThermalResistance)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ThermalResistance)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(ThermalResistance)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(ThermalResistance)) + return this; + else if (conversionType == typeof(ThermalResistanceUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return ThermalResistance.Info; + else if (conversionType == typeof(BaseDimensions)) + return ThermalResistance.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(ThermalResistance)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistanceUnit.g.cs b/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistanceUnit.g.cs new file mode 100644 index 0000000000..3fdcc10310 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/ThermalResistance/ThermalResistanceUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum ThermalResistanceUnit + { + HourSquareFeetDegreeFahrenheitPerBtu = 1, + SquareCentimeterHourDegreeCelsiusPerKilocalorie = 2, + SquareCentimeterKelvinPerWatt = 3, + SquareMeterDegreeCelsiusPerWatt = 4, + SquareMeterKelvinPerKilowatt = 5, + SquareMeterKelvinPerWatt = 6, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Torque/Torque.csproj b/UnitsNet.Modular/GeneratedCode/Torque/Torque.csproj new file mode 100644 index 0000000000..66d36a019b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Torque/Torque.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Torque</Title> + <Description>Adds Torque units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>torque unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{3b6bbc8a-1b22-deff-2980-53b77b6f3e5f}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Torque</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Torque/Torque.g.cs b/UnitsNet.Modular/GeneratedCode/Torque/Torque.g.cs new file mode 100644 index 0000000000..8b1171ac58 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Torque/Torque.g.cs @@ -0,0 +1,1345 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Torque : IArithmeticQuantity<Torque, TorqueUnit, double>, IEquatable<Torque>, IComparable, IComparable<Torque>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TorqueUnit? _unit; + + static Torque() + { + BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + BaseUnit = TorqueUnit.NewtonMeter; + Units = Enum.GetValues(typeof(TorqueUnit)).Cast<TorqueUnit>().ToArray(); + Zero = new Torque(0, BaseUnit); + Info = new QuantityInfo<TorqueUnit>("Torque", + new UnitInfo<TorqueUnit>[] + { + new UnitInfo<TorqueUnit>(TorqueUnit.GramForceCentimeter, "GramForceCentimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.GramForceMeter, "GramForceMeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.GramForceMillimeter, "GramForceMillimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilogramForceCentimeter, "KilogramForceCentimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilogramForceMeter, "KilogramForceMeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilogramForceMillimeter, "KilogramForceMillimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilonewtonCentimeter, "KilonewtonCentimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilonewtonMeter, "KilonewtonMeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilonewtonMillimeter, "KilonewtonMillimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilopoundForceFoot, "KilopoundForceFeet", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.KilopoundForceInch, "KilopoundForceInches", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.MeganewtonCentimeter, "MeganewtonCentimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.MeganewtonMeter, "MeganewtonMeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.MeganewtonMillimeter, "MeganewtonMillimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.MegapoundForceFoot, "MegapoundForceFeet", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.MegapoundForceInch, "MegapoundForceInches", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.NewtonCentimeter, "NewtonCentimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.NewtonMeter, "NewtonMeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.NewtonMillimeter, "NewtonMillimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.PoundalFoot, "PoundalFeet", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.PoundForceFoot, "PoundForceFeet", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.PoundForceInch, "PoundForceInches", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.TonneForceCentimeter, "TonneForceCentimeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.TonneForceMeter, "TonneForceMeters", BaseUnits.Undefined), + new UnitInfo<TorqueUnit>(TorqueUnit.TonneForceMillimeter, "TonneForceMillimeters", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Torque(double value, TorqueUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Torque" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TorqueUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. + /// </summary> + public static TorqueUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Torque quantity. + /// </summary> + public static TorqueUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. + /// </summary> + public static Torque Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Torque AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TorqueUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Torque.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.GramForceCentimeter"/> + /// </summary> + public double GramForceCentimeters => As(TorqueUnit.GramForceCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.GramForceMeter"/> + /// </summary> + public double GramForceMeters => As(TorqueUnit.GramForceMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.GramForceMillimeter"/> + /// </summary> + public double GramForceMillimeters => As(TorqueUnit.GramForceMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilogramForceCentimeter"/> + /// </summary> + public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilogramForceMeter"/> + /// </summary> + public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilogramForceMillimeter"/> + /// </summary> + public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilonewtonCentimeter"/> + /// </summary> + public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilonewtonMeter"/> + /// </summary> + public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilonewtonMillimeter"/> + /// </summary> + public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilopoundForceFoot"/> + /// </summary> + public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.KilopoundForceInch"/> + /// </summary> + public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.MeganewtonCentimeter"/> + /// </summary> + public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.MeganewtonMeter"/> + /// </summary> + public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.MeganewtonMillimeter"/> + /// </summary> + public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.MegapoundForceFoot"/> + /// </summary> + public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.MegapoundForceInch"/> + /// </summary> + public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.NewtonCentimeter"/> + /// </summary> + public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.NewtonMeter"/> + /// </summary> + public double NewtonMeters => As(TorqueUnit.NewtonMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.NewtonMillimeter"/> + /// </summary> + public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.PoundalFoot"/> + /// </summary> + public double PoundalFeet => As(TorqueUnit.PoundalFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.PoundForceFoot"/> + /// </summary> + public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.PoundForceInch"/> + /// </summary> + public double PoundForceInches => As(TorqueUnit.PoundForceInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.TonneForceCentimeter"/> + /// </summary> + public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.TonneForceMeter"/> + /// </summary> + public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorqueUnit.TonneForceMillimeter"/> + /// </summary> + public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TorqueUnit -> BaseUnit + unitConverter.SetConversionFunction<Torque>(TorqueUnit.GramForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.GramForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.GramForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilogramForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilogramForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilogramForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilonewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilonewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilonewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilopoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.KilopoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.MeganewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.MeganewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.MeganewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.MegapoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.MegapoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.PoundalFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.PoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.PoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.TonneForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.TonneForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.TonneForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> TorqueUnit + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.GramForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.GramForceCentimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMeter, quantity => quantity.ToUnit(TorqueUnit.GramForceMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.GramForceMillimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceCentimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceMillimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonCentimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonMillimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.KilopoundForceFoot)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceInch, quantity => quantity.ToUnit(TorqueUnit.KilopoundForceInch)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonCentimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonMillimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.MegapoundForceFoot)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceInch, quantity => quantity.ToUnit(TorqueUnit.MegapoundForceInch)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.NewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.NewtonCentimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMillimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.PoundalFoot, quantity => quantity.ToUnit(TorqueUnit.PoundalFoot)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.PoundForceFoot)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceInch, quantity => quantity.ToUnit(TorqueUnit.PoundForceInch)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceCentimeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceMeter)); + unitConverter.SetConversionFunction<Torque>(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceMillimeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.GramForceCentimeter, new CultureInfo("en-US"), false, true, new string[]{"gf·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.GramForceMeter, new CultureInfo("en-US"), false, true, new string[]{"gf·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.GramForceMillimeter, new CultureInfo("en-US"), false, true, new string[]{"gf·mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilogramForceCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilogramForceMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilogramForceMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kgf·mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilonewtonCentimeter, new CultureInfo("en-US"), false, true, new string[]{"kN·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilonewtonMeter, new CultureInfo("en-US"), false, true, new string[]{"kN·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilonewtonMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кН·м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilonewtonMillimeter, new CultureInfo("en-US"), false, true, new string[]{"kN·mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilopoundForceFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf·ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.KilopoundForceInch, new CultureInfo("en-US"), false, true, new string[]{"kipf·in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.MeganewtonCentimeter, new CultureInfo("en-US"), false, true, new string[]{"MN·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.MeganewtonMeter, new CultureInfo("en-US"), false, true, new string[]{"MN·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.MeganewtonMeter, new CultureInfo("ru-RU"), false, true, new string[]{"МН·м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.MeganewtonMillimeter, new CultureInfo("en-US"), false, true, new string[]{"MN·mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.MegapoundForceFoot, new CultureInfo("en-US"), false, true, new string[]{"Mlbf·ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.MegapoundForceInch, new CultureInfo("en-US"), false, true, new string[]{"Mlbf·in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.NewtonCentimeter, new CultureInfo("en-US"), false, true, new string[]{"N·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.NewtonMeter, new CultureInfo("en-US"), false, true, new string[]{"N·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.NewtonMeter, new CultureInfo("ru-RU"), false, true, new string[]{"Н·м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.NewtonMillimeter, new CultureInfo("en-US"), false, true, new string[]{"N·mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.PoundalFoot, new CultureInfo("en-US"), false, true, new string[]{"pdl·ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.PoundForceFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf·ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.PoundForceInch, new CultureInfo("en-US"), false, true, new string[]{"lbf·in"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.TonneForceCentimeter, new CultureInfo("en-US"), false, true, new string[]{"tf·cm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.TonneForceMeter, new CultureInfo("en-US"), false, true, new string[]{"tf·m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorqueUnit.TonneForceMillimeter, new CultureInfo("en-US"), false, true, new string[]{"tf·mm"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TorqueUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TorqueUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.GramForceCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromGramForceCentimeters(QuantityValue gramforcecentimeters) + { + double value = (double) gramforcecentimeters; + return new Torque(value, TorqueUnit.GramForceCentimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.GramForceMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromGramForceMeters(QuantityValue gramforcemeters) + { + double value = (double) gramforcemeters; + return new Torque(value, TorqueUnit.GramForceMeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.GramForceMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromGramForceMillimeters(QuantityValue gramforcemillimeters) + { + double value = (double) gramforcemillimeters; + return new Torque(value, TorqueUnit.GramForceMillimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilogramForceCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) + { + double value = (double) kilogramforcecentimeters; + return new Torque(value, TorqueUnit.KilogramForceCentimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilogramForceMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) + { + double value = (double) kilogramforcemeters; + return new Torque(value, TorqueUnit.KilogramForceMeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilogramForceMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) + { + double value = (double) kilogramforcemillimeters; + return new Torque(value, TorqueUnit.KilogramForceMillimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilonewtonCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) + { + double value = (double) kilonewtoncentimeters; + return new Torque(value, TorqueUnit.KilonewtonCentimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilonewtonMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) + { + double value = (double) kilonewtonmeters; + return new Torque(value, TorqueUnit.KilonewtonMeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilonewtonMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) + { + double value = (double) kilonewtonmillimeters; + return new Torque(value, TorqueUnit.KilonewtonMillimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilopoundForceFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) + { + double value = (double) kilopoundforcefeet; + return new Torque(value, TorqueUnit.KilopoundForceFoot); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.KilopoundForceInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) + { + double value = (double) kilopoundforceinches; + return new Torque(value, TorqueUnit.KilopoundForceInch); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.MeganewtonCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) + { + double value = (double) meganewtoncentimeters; + return new Torque(value, TorqueUnit.MeganewtonCentimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.MeganewtonMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) + { + double value = (double) meganewtonmeters; + return new Torque(value, TorqueUnit.MeganewtonMeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.MeganewtonMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) + { + double value = (double) meganewtonmillimeters; + return new Torque(value, TorqueUnit.MeganewtonMillimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.MegapoundForceFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) + { + double value = (double) megapoundforcefeet; + return new Torque(value, TorqueUnit.MegapoundForceFoot); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.MegapoundForceInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) + { + double value = (double) megapoundforceinches; + return new Torque(value, TorqueUnit.MegapoundForceInch); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.NewtonCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) + { + double value = (double) newtoncentimeters; + return new Torque(value, TorqueUnit.NewtonCentimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.NewtonMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromNewtonMeters(QuantityValue newtonmeters) + { + double value = (double) newtonmeters; + return new Torque(value, TorqueUnit.NewtonMeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.NewtonMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) + { + double value = (double) newtonmillimeters; + return new Torque(value, TorqueUnit.NewtonMillimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.PoundalFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromPoundalFeet(QuantityValue poundalfeet) + { + double value = (double) poundalfeet; + return new Torque(value, TorqueUnit.PoundalFoot); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.PoundForceFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) + { + double value = (double) poundforcefeet; + return new Torque(value, TorqueUnit.PoundForceFoot); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.PoundForceInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromPoundForceInches(QuantityValue poundforceinches) + { + double value = (double) poundforceinches; + return new Torque(value, TorqueUnit.PoundForceInch); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.TonneForceCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) + { + double value = (double) tonneforcecentimeters; + return new Torque(value, TorqueUnit.TonneForceCentimeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.TonneForceMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) + { + double value = (double) tonneforcemeters; + return new Torque(value, TorqueUnit.TonneForceMeter); + } + + /// <summary> + /// Creates a <see cref="Torque"/> from <see cref="TorqueUnit.TonneForceMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) + { + double value = (double) tonneforcemillimeters; + return new Torque(value, TorqueUnit.TonneForceMillimeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TorqueUnit" /> to <see cref="Torque" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Torque unit value.</returns> + public static Torque From(QuantityValue value, TorqueUnit fromUnit) + { + return new Torque((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Torque Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Torque Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Torque, TorqueUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Torque result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Torque result) + { + return QuantityParser.Default.TryParse<Torque, TorqueUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TorqueUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TorqueUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TorqueUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TorqueUnit)"/> + public static bool TryParseUnit(string str, out TorqueUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TorqueUnit unit) + { + return UnitParser.Default.TryParse<TorqueUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Torque operator -(Torque right) + { + return new Torque(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Torque"/> from adding two <see cref="Torque"/>.</summary> + public static Torque operator +(Torque left, Torque right) + { + return new Torque(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Torque"/> from subtracting two <see cref="Torque"/>.</summary> + public static Torque operator -(Torque left, Torque right) + { + return new Torque(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Torque"/> from multiplying value and <see cref="Torque"/>.</summary> + public static Torque operator *(double left, Torque right) + { + return new Torque(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Torque"/> from multiplying value and <see cref="Torque"/>.</summary> + public static Torque operator *(Torque left, double right) + { + return new Torque(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Torque"/> from dividing <see cref="Torque"/> by value.</summary> + public static Torque operator /(Torque left, double right) + { + return new Torque(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Torque"/> by <see cref="Torque"/>.</summary> + public static double operator /(Torque left, Torque right) + { + return left.NewtonMeters / right.NewtonMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Torque left, Torque right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Torque left, Torque right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Torque left, Torque right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Torque left, Torque right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Torque"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Torque, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Torque left, Torque right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Torque"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Torque, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Torque left, Torque right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Torque"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Torque, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Torque otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Torque"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Torque, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Torque other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Torque"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Torque otherQuantity)) throw new ArgumentException("Expected type Torque.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Torque"/> with another <see cref="Torque"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Torque other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Torque within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Torque.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TorqueUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TorqueUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Torque to another Torque with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Torque with the specified unit.</returns> + public Torque ToUnit(TorqueUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Torque"/> to another <see cref="Torque"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Torque with the specified unit.</returns> + public Torque ToUnit(TorqueUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Torque), Unit, typeof(Torque), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Torque)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Torque"/> to another <see cref="Torque"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Torque"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TorqueUnit unit, [NotNullWhen(true)] out Torque? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Torque? convertedOrNull = (Unit, unit) switch + { + // TorqueUnit -> BaseUnit + (TorqueUnit.GramForceCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-5, TorqueUnit.NewtonMeter), + (TorqueUnit.GramForceMeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-3, TorqueUnit.NewtonMeter), + (TorqueUnit.GramForceMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-6, TorqueUnit.NewtonMeter), + (TorqueUnit.KilogramForceCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-2, TorqueUnit.NewtonMeter), + (TorqueUnit.KilogramForceMeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665, TorqueUnit.NewtonMeter), + (TorqueUnit.KilogramForceMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-3, TorqueUnit.NewtonMeter), + (TorqueUnit.KilonewtonCentimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.01) * 1e3d, TorqueUnit.NewtonMeter), + (TorqueUnit.KilonewtonMeter, TorqueUnit.NewtonMeter) => new Torque((_value) * 1e3d, TorqueUnit.NewtonMeter), + (TorqueUnit.KilonewtonMillimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.001) * 1e3d, TorqueUnit.NewtonMeter), + (TorqueUnit.KilopoundForceFoot, TorqueUnit.NewtonMeter) => new Torque((_value * 1.3558179483314) * 1e3d, TorqueUnit.NewtonMeter), + (TorqueUnit.KilopoundForceInch, TorqueUnit.NewtonMeter) => new Torque((_value * 1.129848290276167e-1) * 1e3d, TorqueUnit.NewtonMeter), + (TorqueUnit.MeganewtonCentimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.01) * 1e6d, TorqueUnit.NewtonMeter), + (TorqueUnit.MeganewtonMeter, TorqueUnit.NewtonMeter) => new Torque((_value) * 1e6d, TorqueUnit.NewtonMeter), + (TorqueUnit.MeganewtonMillimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.001) * 1e6d, TorqueUnit.NewtonMeter), + (TorqueUnit.MegapoundForceFoot, TorqueUnit.NewtonMeter) => new Torque((_value * 1.3558179483314) * 1e6d, TorqueUnit.NewtonMeter), + (TorqueUnit.MegapoundForceInch, TorqueUnit.NewtonMeter) => new Torque((_value * 1.129848290276167e-1) * 1e6d, TorqueUnit.NewtonMeter), + (TorqueUnit.NewtonCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 0.01, TorqueUnit.NewtonMeter), + (TorqueUnit.NewtonMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 0.001, TorqueUnit.NewtonMeter), + (TorqueUnit.PoundalFoot, TorqueUnit.NewtonMeter) => new Torque(_value * 4.21401100938048e-2, TorqueUnit.NewtonMeter), + (TorqueUnit.PoundForceFoot, TorqueUnit.NewtonMeter) => new Torque(_value * 1.3558179483314, TorqueUnit.NewtonMeter), + (TorqueUnit.PoundForceInch, TorqueUnit.NewtonMeter) => new Torque(_value * 1.129848290276167e-1, TorqueUnit.NewtonMeter), + (TorqueUnit.TonneForceCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e1, TorqueUnit.NewtonMeter), + (TorqueUnit.TonneForceMeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e3, TorqueUnit.NewtonMeter), + (TorqueUnit.TonneForceMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665, TorqueUnit.NewtonMeter), + + // BaseUnit -> TorqueUnit + (TorqueUnit.NewtonMeter, TorqueUnit.GramForceCentimeter) => new Torque(_value / 9.80665e-5, TorqueUnit.GramForceCentimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.GramForceMeter) => new Torque(_value / 9.80665e-3, TorqueUnit.GramForceMeter), + (TorqueUnit.NewtonMeter, TorqueUnit.GramForceMillimeter) => new Torque(_value / 9.80665e-6, TorqueUnit.GramForceMillimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceCentimeter) => new Torque(_value / 9.80665e-2, TorqueUnit.KilogramForceCentimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMeter) => new Torque(_value / 9.80665, TorqueUnit.KilogramForceMeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMillimeter) => new Torque(_value / 9.80665e-3, TorqueUnit.KilogramForceMillimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonCentimeter) => new Torque((_value * 100) / 1e3d, TorqueUnit.KilonewtonCentimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMeter) => new Torque((_value) / 1e3d, TorqueUnit.KilonewtonMeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMillimeter) => new Torque((_value * 1000) / 1e3d, TorqueUnit.KilonewtonMillimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceFoot) => new Torque((_value / 1.3558179483314) / 1e3d, TorqueUnit.KilopoundForceFoot), + (TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceInch) => new Torque((_value / 1.129848290276167e-1) / 1e3d, TorqueUnit.KilopoundForceInch), + (TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonCentimeter) => new Torque((_value * 100) / 1e6d, TorqueUnit.MeganewtonCentimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMeter) => new Torque((_value) / 1e6d, TorqueUnit.MeganewtonMeter), + (TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMillimeter) => new Torque((_value * 1000) / 1e6d, TorqueUnit.MeganewtonMillimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceFoot) => new Torque((_value / 1.3558179483314) / 1e6d, TorqueUnit.MegapoundForceFoot), + (TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceInch) => new Torque((_value / 1.129848290276167e-1) / 1e6d, TorqueUnit.MegapoundForceInch), + (TorqueUnit.NewtonMeter, TorqueUnit.NewtonCentimeter) => new Torque(_value * 100, TorqueUnit.NewtonCentimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.NewtonMillimeter) => new Torque(_value * 1000, TorqueUnit.NewtonMillimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.PoundalFoot) => new Torque(_value / 4.21401100938048e-2, TorqueUnit.PoundalFoot), + (TorqueUnit.NewtonMeter, TorqueUnit.PoundForceFoot) => new Torque(_value / 1.3558179483314, TorqueUnit.PoundForceFoot), + (TorqueUnit.NewtonMeter, TorqueUnit.PoundForceInch) => new Torque(_value / 1.129848290276167e-1, TorqueUnit.PoundForceInch), + (TorqueUnit.NewtonMeter, TorqueUnit.TonneForceCentimeter) => new Torque(_value / 9.80665e1, TorqueUnit.TonneForceCentimeter), + (TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMeter) => new Torque(_value / 9.80665e3, TorqueUnit.TonneForceMeter), + (TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMillimeter) => new Torque(_value / 9.80665, TorqueUnit.TonneForceMillimeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TorqueUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TorqueUnit> IQuantity<TorqueUnit>.ToUnit(TorqueUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TorqueUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Torque)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Torque)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Torque)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Torque)) + return this; + else if (conversionType == typeof(TorqueUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Torque.Info; + else if (conversionType == typeof(BaseDimensions)) + return Torque.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Torque)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Torque/TorqueUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Torque/TorqueUnit.g.cs new file mode 100644 index 0000000000..74ad9eb231 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Torque/TorqueUnit.g.cs @@ -0,0 +1,56 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TorqueUnit + { + GramForceCentimeter = 1, + GramForceMeter = 2, + GramForceMillimeter = 3, + KilogramForceCentimeter = 4, + KilogramForceMeter = 5, + KilogramForceMillimeter = 6, + KilonewtonCentimeter = 7, + KilonewtonMeter = 8, + KilonewtonMillimeter = 9, + KilopoundForceFoot = 10, + KilopoundForceInch = 11, + MeganewtonCentimeter = 12, + MeganewtonMeter = 13, + MeganewtonMillimeter = 14, + MegapoundForceFoot = 15, + MegapoundForceInch = 16, + NewtonCentimeter = 17, + NewtonMeter = 18, + NewtonMillimeter = 19, + PoundalFoot = 20, + PoundForceFoot = 21, + PoundForceInch = 22, + TonneForceCentimeter = 23, + TonneForceMeter = 24, + TonneForceMillimeter = 25, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLength.csproj b/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLength.csproj new file mode 100644 index 0000000000..57756abadd --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLength.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET TorquePerLength</Title> + <Description>Adds TorquePerLength units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>torqueperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c27e1919-64f1-ce81-c6d9-b46ced745a12}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.TorquePerLength</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLength.g.cs b/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLength.g.cs new file mode 100644 index 0000000000..f2e554bdb5 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLength.g.cs @@ -0,0 +1,1261 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The magnitude of torque per unit length. + /// </summary> + [DataContract] + public readonly partial struct TorquePerLength : IArithmeticQuantity<TorquePerLength, TorquePerLengthUnit, double>, IEquatable<TorquePerLength>, IComparable, IComparable<TorquePerLength>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TorquePerLengthUnit? _unit; + + static TorquePerLength() + { + BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + BaseUnit = TorquePerLengthUnit.NewtonMeterPerMeter; + Units = Enum.GetValues(typeof(TorquePerLengthUnit)).Cast<TorquePerLengthUnit>().ToArray(); + Zero = new TorquePerLength(0, BaseUnit); + Info = new QuantityInfo<TorquePerLengthUnit>("TorquePerLength", + new UnitInfo<TorquePerLengthUnit>[] + { + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilogramForceCentimeterPerMeter, "KilogramForceCentimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilogramForceMeterPerMeter, "KilogramForceMetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilogramForceMillimeterPerMeter, "KilogramForceMillimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilonewtonCentimeterPerMeter, "KilonewtonCentimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilonewtonMeterPerMeter, "KilonewtonMetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilonewtonMillimeterPerMeter, "KilonewtonMillimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilopoundForceFootPerFoot, "KilopoundForceFeetPerFoot", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.KilopoundForceInchPerFoot, "KilopoundForceInchesPerFoot", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.MeganewtonCentimeterPerMeter, "MeganewtonCentimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.MeganewtonMeterPerMeter, "MeganewtonMetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.MeganewtonMillimeterPerMeter, "MeganewtonMillimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.MegapoundForceFootPerFoot, "MegapoundForceFeetPerFoot", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.MegapoundForceInchPerFoot, "MegapoundForceInchesPerFoot", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.NewtonCentimeterPerMeter, "NewtonCentimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.NewtonMeterPerMeter, "NewtonMetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.NewtonMillimeterPerMeter, "NewtonMillimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.PoundForceFootPerFoot, "PoundForceFeetPerFoot", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.PoundForceInchPerFoot, "PoundForceInchesPerFoot", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.TonneForceCentimeterPerMeter, "TonneForceCentimetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.TonneForceMeterPerMeter, "TonneForceMetersPerMeter", BaseUnits.Undefined), + new UnitInfo<TorquePerLengthUnit>(TorquePerLengthUnit.TonneForceMillimeterPerMeter, "TonneForceMillimetersPerMeter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public TorquePerLength(double value, TorquePerLengthUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="TorquePerLength" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TorquePerLengthUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of TorquePerLength, which is NewtonMeterPerMeter. All conversions go via this value. + /// </summary> + public static TorquePerLengthUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the TorquePerLength quantity. + /// </summary> + public static TorquePerLengthUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerMeter. + /// </summary> + public static TorquePerLength Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static TorquePerLength AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TorquePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TorquePerLengthUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => TorquePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilogramForceCentimeterPerMeter"/> + /// </summary> + public double KilogramForceCentimetersPerMeter => As(TorquePerLengthUnit.KilogramForceCentimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilogramForceMeterPerMeter"/> + /// </summary> + public double KilogramForceMetersPerMeter => As(TorquePerLengthUnit.KilogramForceMeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilogramForceMillimeterPerMeter"/> + /// </summary> + public double KilogramForceMillimetersPerMeter => As(TorquePerLengthUnit.KilogramForceMillimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilonewtonCentimeterPerMeter"/> + /// </summary> + public double KilonewtonCentimetersPerMeter => As(TorquePerLengthUnit.KilonewtonCentimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilonewtonMeterPerMeter"/> + /// </summary> + public double KilonewtonMetersPerMeter => As(TorquePerLengthUnit.KilonewtonMeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilonewtonMillimeterPerMeter"/> + /// </summary> + public double KilonewtonMillimetersPerMeter => As(TorquePerLengthUnit.KilonewtonMillimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilopoundForceFootPerFoot"/> + /// </summary> + public double KilopoundForceFeetPerFoot => As(TorquePerLengthUnit.KilopoundForceFootPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.KilopoundForceInchPerFoot"/> + /// </summary> + public double KilopoundForceInchesPerFoot => As(TorquePerLengthUnit.KilopoundForceInchPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.MeganewtonCentimeterPerMeter"/> + /// </summary> + public double MeganewtonCentimetersPerMeter => As(TorquePerLengthUnit.MeganewtonCentimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.MeganewtonMeterPerMeter"/> + /// </summary> + public double MeganewtonMetersPerMeter => As(TorquePerLengthUnit.MeganewtonMeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.MeganewtonMillimeterPerMeter"/> + /// </summary> + public double MeganewtonMillimetersPerMeter => As(TorquePerLengthUnit.MeganewtonMillimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.MegapoundForceFootPerFoot"/> + /// </summary> + public double MegapoundForceFeetPerFoot => As(TorquePerLengthUnit.MegapoundForceFootPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.MegapoundForceInchPerFoot"/> + /// </summary> + public double MegapoundForceInchesPerFoot => As(TorquePerLengthUnit.MegapoundForceInchPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.NewtonCentimeterPerMeter"/> + /// </summary> + public double NewtonCentimetersPerMeter => As(TorquePerLengthUnit.NewtonCentimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.NewtonMeterPerMeter"/> + /// </summary> + public double NewtonMetersPerMeter => As(TorquePerLengthUnit.NewtonMeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.NewtonMillimeterPerMeter"/> + /// </summary> + public double NewtonMillimetersPerMeter => As(TorquePerLengthUnit.NewtonMillimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.PoundForceFootPerFoot"/> + /// </summary> + public double PoundForceFeetPerFoot => As(TorquePerLengthUnit.PoundForceFootPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.PoundForceInchPerFoot"/> + /// </summary> + public double PoundForceInchesPerFoot => As(TorquePerLengthUnit.PoundForceInchPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.TonneForceCentimeterPerMeter"/> + /// </summary> + public double TonneForceCentimetersPerMeter => As(TorquePerLengthUnit.TonneForceCentimeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.TonneForceMeterPerMeter"/> + /// </summary> + public double TonneForceMetersPerMeter => As(TorquePerLengthUnit.TonneForceMeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TorquePerLengthUnit.TonneForceMillimeterPerMeter"/> + /// </summary> + public double TonneForceMillimetersPerMeter => As(TorquePerLengthUnit.TonneForceMillimeterPerMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TorquePerLengthUnit -> BaseUnit + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilogramForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilogramForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilogramForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilonewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilonewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilonewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilopoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.KilopoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.MeganewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.MeganewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.MeganewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.MegapoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.MegapoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.PoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.PoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.TonneForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.TonneForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.TonneForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMeterPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> TorquePerLengthUnit + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilogramForceCentimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilogramForceMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilogramForceMillimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilonewtonCentimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilonewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.KilonewtonMillimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceFootPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.KilopoundForceFootPerFoot)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceInchPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.KilopoundForceInchPerFoot)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.MeganewtonCentimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.MeganewtonMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.MeganewtonMillimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceFootPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.MegapoundForceFootPerFoot)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceInchPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.MegapoundForceInchPerFoot)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonCentimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.NewtonMillimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceFootPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.PoundForceFootPerFoot)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceInchPerFoot, quantity => quantity.ToUnit(TorquePerLengthUnit.PoundForceInchPerFoot)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceCentimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.TonneForceCentimeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.TonneForceMeterPerMeter)); + unitConverter.SetConversionFunction<TorquePerLength>(TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMillimeterPerMeter, quantity => quantity.ToUnit(TorquePerLengthUnit.TonneForceMillimeterPerMeter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilogramForceCentimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf·cm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilogramForceMeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf·m/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilogramForceMillimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kgf·mm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilonewtonCentimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kN·cm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilonewtonMeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kN·m/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilonewtonMeterPerMeter, new CultureInfo("ru-RU"), false, true, new string[]{"кН·м/м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilonewtonMillimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"kN·mm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilopoundForceFootPerFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf·ft/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.KilopoundForceInchPerFoot, new CultureInfo("en-US"), false, true, new string[]{"kipf·in/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.MeganewtonCentimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"MN·cm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.MeganewtonMeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"MN·m/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.MeganewtonMeterPerMeter, new CultureInfo("ru-RU"), false, true, new string[]{"МН·м/м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.MeganewtonMillimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"MN·mm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.MegapoundForceFootPerFoot, new CultureInfo("en-US"), false, true, new string[]{"Mlbf·ft/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.MegapoundForceInchPerFoot, new CultureInfo("en-US"), false, true, new string[]{"Mlbf·in/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.NewtonCentimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"N·cm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.NewtonMeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"N·m/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.NewtonMeterPerMeter, new CultureInfo("ru-RU"), false, true, new string[]{"Н·м/м"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.NewtonMillimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"N·mm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.PoundForceFootPerFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf·ft/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.PoundForceInchPerFoot, new CultureInfo("en-US"), false, true, new string[]{"lbf·in/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.TonneForceCentimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"tf·cm/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.TonneForceMeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"tf·m/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(TorquePerLengthUnit.TonneForceMillimeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"tf·mm/m"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TorquePerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TorquePerLengthUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilogramForceCentimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilogramForceCentimetersPerMeter(QuantityValue kilogramforcecentimeterspermeter) + { + double value = (double) kilogramforcecentimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceCentimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilogramForceMeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilogramForceMetersPerMeter(QuantityValue kilogramforcemeterspermeter) + { + double value = (double) kilogramforcemeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceMeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilogramForceMillimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilogramForceMillimetersPerMeter(QuantityValue kilogramforcemillimeterspermeter) + { + double value = (double) kilogramforcemillimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.KilogramForceMillimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilonewtonCentimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilonewtonCentimetersPerMeter(QuantityValue kilonewtoncentimeterspermeter) + { + double value = (double) kilonewtoncentimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonCentimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilonewtonMeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilonewtonMetersPerMeter(QuantityValue kilonewtonmeterspermeter) + { + double value = (double) kilonewtonmeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonMeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilonewtonMillimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilonewtonMillimetersPerMeter(QuantityValue kilonewtonmillimeterspermeter) + { + double value = (double) kilonewtonmillimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.KilonewtonMillimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilopoundForceFootPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilopoundForceFeetPerFoot(QuantityValue kilopoundforcefeetperfoot) + { + double value = (double) kilopoundforcefeetperfoot; + return new TorquePerLength(value, TorquePerLengthUnit.KilopoundForceFootPerFoot); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.KilopoundForceInchPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromKilopoundForceInchesPerFoot(QuantityValue kilopoundforceinchesperfoot) + { + double value = (double) kilopoundforceinchesperfoot; + return new TorquePerLength(value, TorquePerLengthUnit.KilopoundForceInchPerFoot); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.MeganewtonCentimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromMeganewtonCentimetersPerMeter(QuantityValue meganewtoncentimeterspermeter) + { + double value = (double) meganewtoncentimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonCentimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.MeganewtonMeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromMeganewtonMetersPerMeter(QuantityValue meganewtonmeterspermeter) + { + double value = (double) meganewtonmeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonMeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.MeganewtonMillimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromMeganewtonMillimetersPerMeter(QuantityValue meganewtonmillimeterspermeter) + { + double value = (double) meganewtonmillimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.MeganewtonMillimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.MegapoundForceFootPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromMegapoundForceFeetPerFoot(QuantityValue megapoundforcefeetperfoot) + { + double value = (double) megapoundforcefeetperfoot; + return new TorquePerLength(value, TorquePerLengthUnit.MegapoundForceFootPerFoot); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.MegapoundForceInchPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromMegapoundForceInchesPerFoot(QuantityValue megapoundforceinchesperfoot) + { + double value = (double) megapoundforceinchesperfoot; + return new TorquePerLength(value, TorquePerLengthUnit.MegapoundForceInchPerFoot); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.NewtonCentimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromNewtonCentimetersPerMeter(QuantityValue newtoncentimeterspermeter) + { + double value = (double) newtoncentimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.NewtonCentimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.NewtonMeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromNewtonMetersPerMeter(QuantityValue newtonmeterspermeter) + { + double value = (double) newtonmeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.NewtonMeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.NewtonMillimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromNewtonMillimetersPerMeter(QuantityValue newtonmillimeterspermeter) + { + double value = (double) newtonmillimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.NewtonMillimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.PoundForceFootPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromPoundForceFeetPerFoot(QuantityValue poundforcefeetperfoot) + { + double value = (double) poundforcefeetperfoot; + return new TorquePerLength(value, TorquePerLengthUnit.PoundForceFootPerFoot); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.PoundForceInchPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromPoundForceInchesPerFoot(QuantityValue poundforceinchesperfoot) + { + double value = (double) poundforceinchesperfoot; + return new TorquePerLength(value, TorquePerLengthUnit.PoundForceInchPerFoot); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.TonneForceCentimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromTonneForceCentimetersPerMeter(QuantityValue tonneforcecentimeterspermeter) + { + double value = (double) tonneforcecentimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.TonneForceCentimeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.TonneForceMeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromTonneForceMetersPerMeter(QuantityValue tonneforcemeterspermeter) + { + double value = (double) tonneforcemeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.TonneForceMeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="TorquePerLength"/> from <see cref="TorquePerLengthUnit.TonneForceMillimeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static TorquePerLength FromTonneForceMillimetersPerMeter(QuantityValue tonneforcemillimeterspermeter) + { + double value = (double) tonneforcemillimeterspermeter; + return new TorquePerLength(value, TorquePerLengthUnit.TonneForceMillimeterPerMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TorquePerLengthUnit" /> to <see cref="TorquePerLength" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>TorquePerLength unit value.</returns> + public static TorquePerLength From(QuantityValue value, TorquePerLengthUnit fromUnit) + { + return new TorquePerLength((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static TorquePerLength Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static TorquePerLength Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<TorquePerLength, TorquePerLengthUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out TorquePerLength result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out TorquePerLength result) + { + return QuantityParser.Default.TryParse<TorquePerLength, TorquePerLengthUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TorquePerLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TorquePerLengthUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TorquePerLengthUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TorquePerLengthUnit)"/> + public static bool TryParseUnit(string str, out TorquePerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TorquePerLengthUnit unit) + { + return UnitParser.Default.TryParse<TorquePerLengthUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static TorquePerLength operator -(TorquePerLength right) + { + return new TorquePerLength(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="TorquePerLength"/> from adding two <see cref="TorquePerLength"/>.</summary> + public static TorquePerLength operator +(TorquePerLength left, TorquePerLength right) + { + return new TorquePerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TorquePerLength"/> from subtracting two <see cref="TorquePerLength"/>.</summary> + public static TorquePerLength operator -(TorquePerLength left, TorquePerLength right) + { + return new TorquePerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="TorquePerLength"/> from multiplying value and <see cref="TorquePerLength"/>.</summary> + public static TorquePerLength operator *(double left, TorquePerLength right) + { + return new TorquePerLength(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="TorquePerLength"/> from multiplying value and <see cref="TorquePerLength"/>.</summary> + public static TorquePerLength operator *(TorquePerLength left, double right) + { + return new TorquePerLength(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="TorquePerLength"/> from dividing <see cref="TorquePerLength"/> by value.</summary> + public static TorquePerLength operator /(TorquePerLength left, double right) + { + return new TorquePerLength(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="TorquePerLength"/> by <see cref="TorquePerLength"/>.</summary> + public static double operator /(TorquePerLength left, TorquePerLength right) + { + return left.NewtonMetersPerMeter / right.NewtonMetersPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(TorquePerLength left, TorquePerLength right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(TorquePerLength left, TorquePerLength right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(TorquePerLength left, TorquePerLength right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(TorquePerLength left, TorquePerLength right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="TorquePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TorquePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(TorquePerLength left, TorquePerLength right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="TorquePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TorquePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(TorquePerLength left, TorquePerLength right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TorquePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TorquePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is TorquePerLength otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="TorquePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(TorquePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(TorquePerLength other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="TorquePerLength"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is TorquePerLength otherQuantity)) throw new ArgumentException("Expected type TorquePerLength.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="TorquePerLength"/> with another <see cref="TorquePerLength"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(TorquePerLength other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another TorquePerLength within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(TorquePerLength other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current TorquePerLength.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TorquePerLengthUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TorquePerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this TorquePerLength to another TorquePerLength with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A TorquePerLength with the specified unit.</returns> + public TorquePerLength ToUnit(TorquePerLengthUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="TorquePerLength"/> to another <see cref="TorquePerLength"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A TorquePerLength with the specified unit.</returns> + public TorquePerLength ToUnit(TorquePerLengthUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(TorquePerLength), Unit, typeof(TorquePerLength), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (TorquePerLength)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="TorquePerLength"/> to another <see cref="TorquePerLength"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="TorquePerLength"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TorquePerLengthUnit unit, [NotNullWhen(true)] out TorquePerLength? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + TorquePerLength? convertedOrNull = (Unit, unit) switch + { + // TorquePerLengthUnit -> BaseUnit + (TorquePerLengthUnit.KilogramForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 0.0980665019960652, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilogramForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 9.80665019960652, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilogramForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 0.00980665019960652, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilonewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 0.01) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilonewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilonewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 0.001) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilopoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 4.44822161526) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.KilopoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 0.370685147638) * 1e3d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.MeganewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 0.01) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.MeganewtonMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.MeganewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 0.001) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.MegapoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 4.44822161526) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.MegapoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength((_value * 0.370685147638) * 1e6d, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.NewtonCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 0.01, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.NewtonMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 0.001, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.PoundForceFootPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 4.44822161526, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.PoundForceInchPerFoot, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 0.370685147638, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.TonneForceCentimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 98.0665019960652, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.TonneForceMeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 9806.65019960653, TorquePerLengthUnit.NewtonMeterPerMeter), + (TorquePerLengthUnit.TonneForceMillimeterPerMeter, TorquePerLengthUnit.NewtonMeterPerMeter) => new TorquePerLength(_value * 9.80665019960652, TorquePerLengthUnit.NewtonMeterPerMeter), + + // BaseUnit -> TorquePerLengthUnit + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceCentimeterPerMeter) => new TorquePerLength(_value * 10.1971619222242, TorquePerLengthUnit.KilogramForceCentimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMeterPerMeter) => new TorquePerLength(_value * 0.101971619222242, TorquePerLengthUnit.KilogramForceMeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilogramForceMillimeterPerMeter) => new TorquePerLength(_value * 101.971619222242, TorquePerLengthUnit.KilogramForceMillimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonCentimeterPerMeter) => new TorquePerLength((_value * 100) / 1e3d, TorquePerLengthUnit.KilonewtonCentimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMeterPerMeter) => new TorquePerLength((_value) / 1e3d, TorquePerLengthUnit.KilonewtonMeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilonewtonMillimeterPerMeter) => new TorquePerLength((_value * 1000) / 1e3d, TorquePerLengthUnit.KilonewtonMillimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceFootPerFoot) => new TorquePerLength((_value / 4.44822161526) / 1e3d, TorquePerLengthUnit.KilopoundForceFootPerFoot), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.KilopoundForceInchPerFoot) => new TorquePerLength((_value / 0.370685147638) / 1e3d, TorquePerLengthUnit.KilopoundForceInchPerFoot), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonCentimeterPerMeter) => new TorquePerLength((_value * 100) / 1e6d, TorquePerLengthUnit.MeganewtonCentimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMeterPerMeter) => new TorquePerLength((_value) / 1e6d, TorquePerLengthUnit.MeganewtonMeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MeganewtonMillimeterPerMeter) => new TorquePerLength((_value * 1000) / 1e6d, TorquePerLengthUnit.MeganewtonMillimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceFootPerFoot) => new TorquePerLength((_value / 4.44822161526) / 1e6d, TorquePerLengthUnit.MegapoundForceFootPerFoot), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.MegapoundForceInchPerFoot) => new TorquePerLength((_value / 0.370685147638) / 1e6d, TorquePerLengthUnit.MegapoundForceInchPerFoot), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonCentimeterPerMeter) => new TorquePerLength(_value * 100, TorquePerLengthUnit.NewtonCentimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.NewtonMillimeterPerMeter) => new TorquePerLength(_value * 1000, TorquePerLengthUnit.NewtonMillimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceFootPerFoot) => new TorquePerLength(_value / 4.44822161526, TorquePerLengthUnit.PoundForceFootPerFoot), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.PoundForceInchPerFoot) => new TorquePerLength(_value / 0.370685147638, TorquePerLengthUnit.PoundForceInchPerFoot), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceCentimeterPerMeter) => new TorquePerLength(_value * 0.0101971619222242, TorquePerLengthUnit.TonneForceCentimeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMeterPerMeter) => new TorquePerLength(_value * 0.000101971619222242, TorquePerLengthUnit.TonneForceMeterPerMeter), + (TorquePerLengthUnit.NewtonMeterPerMeter, TorquePerLengthUnit.TonneForceMillimeterPerMeter) => new TorquePerLength(_value * 0.101971619222242, TorquePerLengthUnit.TonneForceMillimeterPerMeter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TorquePerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorquePerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TorquePerLengthUnit> IQuantity<TorquePerLengthUnit>.ToUnit(TorquePerLengthUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TorquePerLengthUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TorquePerLength)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TorquePerLength)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(TorquePerLength)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(TorquePerLength)) + return this; + else if (conversionType == typeof(TorquePerLengthUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return TorquePerLength.Info; + else if (conversionType == typeof(BaseDimensions)) + return TorquePerLength.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(TorquePerLength)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLengthUnit.g.cs b/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLengthUnit.g.cs new file mode 100644 index 0000000000..4145084d80 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/TorquePerLength/TorquePerLengthUnit.g.cs @@ -0,0 +1,52 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TorquePerLengthUnit + { + KilogramForceCentimeterPerMeter = 1, + KilogramForceMeterPerMeter = 2, + KilogramForceMillimeterPerMeter = 3, + KilonewtonCentimeterPerMeter = 4, + KilonewtonMeterPerMeter = 5, + KilonewtonMillimeterPerMeter = 6, + KilopoundForceFootPerFoot = 7, + KilopoundForceInchPerFoot = 8, + MeganewtonCentimeterPerMeter = 9, + MeganewtonMeterPerMeter = 10, + MeganewtonMillimeterPerMeter = 11, + MegapoundForceFootPerFoot = 12, + MegapoundForceInchPerFoot = 13, + NewtonCentimeterPerMeter = 14, + NewtonMeterPerMeter = 15, + NewtonMillimeterPerMeter = 16, + PoundForceFootPerFoot = 17, + PoundForceInchPerFoot = 18, + TonneForceCentimeterPerMeter = 19, + TonneForceMeterPerMeter = 20, + TonneForceMillimeterPerMeter = 21, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Turbidity/Turbidity.csproj b/UnitsNet.Modular/GeneratedCode/Turbidity/Turbidity.csproj new file mode 100644 index 0000000000..ce1b8ffb32 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Turbidity/Turbidity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Turbidity</Title> + <Description>Adds Turbidity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>turbidity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{05ac8aed-49a4-5c9f-d8c2-8d2debf64791}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Turbidity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Turbidity/Turbidity.g.cs b/UnitsNet.Modular/GeneratedCode/Turbidity/Turbidity.g.cs new file mode 100644 index 0000000000..5b29d4fb03 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Turbidity/Turbidity.g.cs @@ -0,0 +1,841 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Turbidity is the cloudiness or haziness of a fluid caused by large numbers of individual particles that are generally invisible to the naked eye, similar to smoke in air. The measurement of turbidity is a key test of water quality. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Turbidity + /// </remarks> + [DataContract] + public readonly partial struct Turbidity : IArithmeticQuantity<Turbidity, TurbidityUnit, double>, IEquatable<Turbidity>, IComparable, IComparable<Turbidity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly TurbidityUnit? _unit; + + static Turbidity() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = TurbidityUnit.NTU; + Units = Enum.GetValues(typeof(TurbidityUnit)).Cast<TurbidityUnit>().ToArray(); + Zero = new Turbidity(0, BaseUnit); + Info = new QuantityInfo<TurbidityUnit>("Turbidity", + new UnitInfo<TurbidityUnit>[] + { + new UnitInfo<TurbidityUnit>(TurbidityUnit.NTU, "NTU", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Turbidity(double value, TurbidityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Turbidity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<TurbidityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Turbidity, which is NTU. All conversions go via this value. + /// </summary> + public static TurbidityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Turbidity quantity. + /// </summary> + public static TurbidityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit NTU. + /// </summary> + public static Turbidity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Turbidity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public TurbidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<TurbidityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Turbidity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="TurbidityUnit.NTU"/> + /// </summary> + public double NTU => As(TurbidityUnit.NTU); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: TurbidityUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Turbidity>(TurbidityUnit.NTU, TurbidityUnit.NTU, quantity => quantity); + + // Register in unit converter: BaseUnit -> TurbidityUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(TurbidityUnit.NTU, new CultureInfo("en-US"), false, true, new string[]{"NTU"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(TurbidityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(TurbidityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Turbidity"/> from <see cref="TurbidityUnit.NTU"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Turbidity FromNTU(QuantityValue ntu) + { + double value = (double) ntu; + return new Turbidity(value, TurbidityUnit.NTU); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="TurbidityUnit" /> to <see cref="Turbidity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Turbidity unit value.</returns> + public static Turbidity From(QuantityValue value, TurbidityUnit fromUnit) + { + return new Turbidity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Turbidity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Turbidity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Turbidity, TurbidityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Turbidity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Turbidity result) + { + return QuantityParser.Default.TryParse<Turbidity, TurbidityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TurbidityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static TurbidityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<TurbidityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.TurbidityUnit)"/> + public static bool TryParseUnit(string str, out TurbidityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out TurbidityUnit unit) + { + return UnitParser.Default.TryParse<TurbidityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Turbidity operator -(Turbidity right) + { + return new Turbidity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Turbidity"/> from adding two <see cref="Turbidity"/>.</summary> + public static Turbidity operator +(Turbidity left, Turbidity right) + { + return new Turbidity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Turbidity"/> from subtracting two <see cref="Turbidity"/>.</summary> + public static Turbidity operator -(Turbidity left, Turbidity right) + { + return new Turbidity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Turbidity"/> from multiplying value and <see cref="Turbidity"/>.</summary> + public static Turbidity operator *(double left, Turbidity right) + { + return new Turbidity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Turbidity"/> from multiplying value and <see cref="Turbidity"/>.</summary> + public static Turbidity operator *(Turbidity left, double right) + { + return new Turbidity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Turbidity"/> from dividing <see cref="Turbidity"/> by value.</summary> + public static Turbidity operator /(Turbidity left, double right) + { + return new Turbidity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Turbidity"/> by <see cref="Turbidity"/>.</summary> + public static double operator /(Turbidity left, Turbidity right) + { + return left.NTU / right.NTU; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Turbidity left, Turbidity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Turbidity left, Turbidity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Turbidity left, Turbidity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Turbidity left, Turbidity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Turbidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Turbidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Turbidity left, Turbidity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Turbidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Turbidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Turbidity left, Turbidity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Turbidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Turbidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Turbidity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Turbidity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Turbidity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Turbidity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Turbidity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Turbidity otherQuantity)) throw new ArgumentException("Expected type Turbidity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Turbidity"/> with another <see cref="Turbidity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Turbidity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Turbidity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(Turbidity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Turbidity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(TurbidityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is TurbidityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Turbidity to another Turbidity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Turbidity with the specified unit.</returns> + public Turbidity ToUnit(TurbidityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Turbidity"/> to another <see cref="Turbidity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Turbidity with the specified unit.</returns> + public Turbidity ToUnit(TurbidityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Turbidity), Unit, typeof(Turbidity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Turbidity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Turbidity"/> to another <see cref="Turbidity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Turbidity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(TurbidityUnit unit, [NotNullWhen(true)] out Turbidity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Turbidity? convertedOrNull = (Unit, unit) switch + { + // TurbidityUnit -> BaseUnit + + // BaseUnit -> TurbidityUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is TurbidityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<TurbidityUnit> IQuantity<TurbidityUnit>.ToUnit(TurbidityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<TurbidityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Turbidity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Turbidity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Turbidity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Turbidity)) + return this; + else if (conversionType == typeof(TurbidityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Turbidity.Info; + else if (conversionType == typeof(BaseDimensions)) + return Turbidity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Turbidity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Turbidity/TurbidityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Turbidity/TurbidityUnit.g.cs new file mode 100644 index 0000000000..a511c7c143 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Turbidity/TurbidityUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum TurbidityUnit + { + NTU = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminA.csproj b/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminA.csproj new file mode 100644 index 0000000000..6f28de014a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminA.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET VitaminA</Title> + <Description>Adds VitaminA units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>vitamina unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{c00185af-8735-7674-5fa6-232424b04161}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.VitaminA</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminA.g.cs b/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminA.g.cs new file mode 100644 index 0000000000..d14972bb3e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminA.g.cs @@ -0,0 +1,838 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. + /// </summary> + [DataContract] + public readonly partial struct VitaminA : IArithmeticQuantity<VitaminA, VitaminAUnit, double>, IEquatable<VitaminA>, IComparable, IComparable<VitaminA>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VitaminAUnit? _unit; + + static VitaminA() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = VitaminAUnit.InternationalUnit; + Units = Enum.GetValues(typeof(VitaminAUnit)).Cast<VitaminAUnit>().ToArray(); + Zero = new VitaminA(0, BaseUnit); + Info = new QuantityInfo<VitaminAUnit>("VitaminA", + new UnitInfo<VitaminAUnit>[] + { + new UnitInfo<VitaminAUnit>(VitaminAUnit.InternationalUnit, "InternationalUnits", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public VitaminA(double value, VitaminAUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="VitaminA" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VitaminAUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. + /// </summary> + public static VitaminAUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the VitaminA quantity. + /// </summary> + public static VitaminAUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. + /// </summary> + public static VitaminA Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static VitaminA AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VitaminAUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => VitaminA.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VitaminAUnit.InternationalUnit"/> + /// </summary> + public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VitaminAUnit -> BaseUnit + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<VitaminA>(VitaminAUnit.InternationalUnit, VitaminAUnit.InternationalUnit, quantity => quantity); + + // Register in unit converter: BaseUnit -> VitaminAUnit + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VitaminAUnit.InternationalUnit, new CultureInfo("en-US"), false, true, new string[]{"IU"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VitaminAUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VitaminAUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="VitaminA"/> from <see cref="VitaminAUnit.InternationalUnit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VitaminA FromInternationalUnits(QuantityValue internationalunits) + { + double value = (double) internationalunits; + return new VitaminA(value, VitaminAUnit.InternationalUnit); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VitaminAUnit" /> to <see cref="VitaminA" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>VitaminA unit value.</returns> + public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) + { + return new VitaminA((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static VitaminA Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static VitaminA Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<VitaminA, VitaminAUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out VitaminA result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out VitaminA result) + { + return QuantityParser.Default.TryParse<VitaminA, VitaminAUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VitaminAUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VitaminAUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VitaminAUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VitaminAUnit)"/> + public static bool TryParseUnit(string str, out VitaminAUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VitaminAUnit unit) + { + return UnitParser.Default.TryParse<VitaminAUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static VitaminA operator -(VitaminA right) + { + return new VitaminA(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="VitaminA"/> from adding two <see cref="VitaminA"/>.</summary> + public static VitaminA operator +(VitaminA left, VitaminA right) + { + return new VitaminA(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VitaminA"/> from subtracting two <see cref="VitaminA"/>.</summary> + public static VitaminA operator -(VitaminA left, VitaminA right) + { + return new VitaminA(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VitaminA"/> from multiplying value and <see cref="VitaminA"/>.</summary> + public static VitaminA operator *(double left, VitaminA right) + { + return new VitaminA(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="VitaminA"/> from multiplying value and <see cref="VitaminA"/>.</summary> + public static VitaminA operator *(VitaminA left, double right) + { + return new VitaminA(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="VitaminA"/> from dividing <see cref="VitaminA"/> by value.</summary> + public static VitaminA operator /(VitaminA left, double right) + { + return new VitaminA(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="VitaminA"/> by <see cref="VitaminA"/>.</summary> + public static double operator /(VitaminA left, VitaminA right) + { + return left.InternationalUnits / right.InternationalUnits; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(VitaminA left, VitaminA right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(VitaminA left, VitaminA right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(VitaminA left, VitaminA right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(VitaminA left, VitaminA right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="VitaminA"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VitaminA, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(VitaminA left, VitaminA right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="VitaminA"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VitaminA, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(VitaminA left, VitaminA right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VitaminA"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VitaminA, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is VitaminA otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VitaminA"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VitaminA, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(VitaminA other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="VitaminA"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is VitaminA otherQuantity)) throw new ArgumentException("Expected type VitaminA.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="VitaminA"/> with another <see cref="VitaminA"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(VitaminA other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another VitaminA within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current VitaminA.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VitaminAUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VitaminAUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this VitaminA to another VitaminA with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A VitaminA with the specified unit.</returns> + public VitaminA ToUnit(VitaminAUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="VitaminA"/> to another <see cref="VitaminA"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A VitaminA with the specified unit.</returns> + public VitaminA ToUnit(VitaminAUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(VitaminA), Unit, typeof(VitaminA), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (VitaminA)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="VitaminA"/> to another <see cref="VitaminA"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="VitaminA"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VitaminAUnit unit, [NotNullWhen(true)] out VitaminA? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + VitaminA? convertedOrNull = (Unit, unit) switch + { + // VitaminAUnit -> BaseUnit + + // BaseUnit -> VitaminAUnit + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VitaminAUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VitaminAUnit> IQuantity<VitaminAUnit>.ToUnit(VitaminAUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VitaminAUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VitaminA)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VitaminA)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VitaminA)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(VitaminA)) + return this; + else if (conversionType == typeof(VitaminAUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return VitaminA.Info; + else if (conversionType == typeof(BaseDimensions)) + return VitaminA.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(VitaminA)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminAUnit.g.cs b/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminAUnit.g.cs new file mode 100644 index 0000000000..2ffecd0c47 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VitaminA/VitaminAUnit.g.cs @@ -0,0 +1,32 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VitaminAUnit + { + InternationalUnit = 1, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/Volume/Volume.csproj b/UnitsNet.Modular/GeneratedCode/Volume/Volume.csproj new file mode 100644 index 0000000000..6947a95b7e --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Volume/Volume.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET Volume</Title> + <Description>Adds Volume units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>volume unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{66b90fb1-20d7-f563-3477-4c7c6b404f4d}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.Volume</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/Volume/Volume.g.cs b/UnitsNet.Modular/GeneratedCode/Volume/Volume.g.cs new file mode 100644 index 0000000000..415c2db03a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Volume/Volume.g.cs @@ -0,0 +1,1978 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct Volume : IArithmeticQuantity<Volume, VolumeUnit, double>, IEquatable<Volume>, IComparable, IComparable<Volume>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VolumeUnit? _unit; + + static Volume() + { + BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); + BaseUnit = VolumeUnit.CubicMeter; + Units = Enum.GetValues(typeof(VolumeUnit)).Cast<VolumeUnit>().ToArray(); + Zero = new Volume(0, BaseUnit); + Info = new QuantityInfo<VolumeUnit>("Volume", + new UnitInfo<VolumeUnit>[] + { + new UnitInfo<VolumeUnit>(VolumeUnit.AcreFoot, "AcreFeet", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.AuTablespoon, "AuTablespoons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.BoardFoot, "BoardFeet", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Centiliter, "Centiliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicCentimeter, "CubicCentimeters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicDecimeter, "CubicDecimeters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicFoot, "CubicFeet", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicHectometer, "CubicHectometers", new BaseUnits(length: LengthUnit.Hectometer)), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicInch, "CubicInches", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicKilometer, "CubicKilometers", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicMeter, "CubicMeters", new BaseUnits(length: LengthUnit.Meter)), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicMicrometer, "CubicMicrometers", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicMile, "CubicMiles", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicMillimeter, "CubicMillimeters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.CubicYard, "CubicYards", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Decaliter, "Decaliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.DecausGallon, "DecausGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Deciliter, "Deciliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.DeciusGallon, "DeciusGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.HectocubicFoot, "HectocubicFeet", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.HectocubicMeter, "HectocubicMeters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Hectoliter, "Hectoliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.HectousGallon, "HectousGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.ImperialBeerBarrel, "ImperialBeerBarrels", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.ImperialGallon, "ImperialGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.ImperialOunce, "ImperialOunces", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.ImperialPint, "ImperialPints", new BaseUnits(length: LengthUnit.Decimeter)), + new UnitInfo<VolumeUnit>(VolumeUnit.KilocubicFoot, "KilocubicFeet", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.KilocubicMeter, "KilocubicMeters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.KiloimperialGallon, "KiloimperialGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Kiloliter, "Kiloliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.KilousGallon, "KilousGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Liter, "Liters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.MegacubicFoot, "MegacubicFeet", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.MegaimperialGallon, "MegaimperialGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Megaliter, "Megaliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.MegausGallon, "MegausGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.MetricCup, "MetricCups", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.MetricTeaspoon, "MetricTeaspoons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Microliter, "Microliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Milliliter, "Milliliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.Nanoliter, "Nanoliters", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.OilBarrel, "OilBarrels", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UkTablespoon, "UkTablespoons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsBeerBarrel, "UsBeerBarrels", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsCustomaryCup, "UsCustomaryCups", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsGallon, "UsGallons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsLegalCup, "UsLegalCups", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsOunce, "UsOunces", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsPint, "UsPints", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsQuart, "UsQuarts", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsTablespoon, "UsTablespoons", BaseUnits.Undefined), + new UnitInfo<VolumeUnit>(VolumeUnit.UsTeaspoon, "UsTeaspoons", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public Volume(double value, VolumeUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="Volume" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VolumeUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of Volume, which is CubicMeter. All conversions go via this value. + /// </summary> + public static VolumeUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the Volume quantity. + /// </summary> + public static VolumeUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. + /// </summary> + public static Volume Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static Volume AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VolumeUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => Volume.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.AcreFoot"/> + /// </summary> + public double AcreFeet => As(VolumeUnit.AcreFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.AuTablespoon"/> + /// </summary> + public double AuTablespoons => As(VolumeUnit.AuTablespoon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.BoardFoot"/> + /// </summary> + public double BoardFeet => As(VolumeUnit.BoardFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Centiliter"/> + /// </summary> + public double Centiliters => As(VolumeUnit.Centiliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicCentimeter"/> + /// </summary> + public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicDecimeter"/> + /// </summary> + public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicFoot"/> + /// </summary> + public double CubicFeet => As(VolumeUnit.CubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicHectometer"/> + /// </summary> + public double CubicHectometers => As(VolumeUnit.CubicHectometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicInch"/> + /// </summary> + public double CubicInches => As(VolumeUnit.CubicInch); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicKilometer"/> + /// </summary> + public double CubicKilometers => As(VolumeUnit.CubicKilometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicMeter"/> + /// </summary> + public double CubicMeters => As(VolumeUnit.CubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicMicrometer"/> + /// </summary> + public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicMile"/> + /// </summary> + public double CubicMiles => As(VolumeUnit.CubicMile); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicMillimeter"/> + /// </summary> + public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.CubicYard"/> + /// </summary> + public double CubicYards => As(VolumeUnit.CubicYard); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Decaliter"/> + /// </summary> + public double Decaliters => As(VolumeUnit.Decaliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.DecausGallon"/> + /// </summary> + public double DecausGallons => As(VolumeUnit.DecausGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Deciliter"/> + /// </summary> + public double Deciliters => As(VolumeUnit.Deciliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.DeciusGallon"/> + /// </summary> + public double DeciusGallons => As(VolumeUnit.DeciusGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.HectocubicFoot"/> + /// </summary> + public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.HectocubicMeter"/> + /// </summary> + public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Hectoliter"/> + /// </summary> + public double Hectoliters => As(VolumeUnit.Hectoliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.HectousGallon"/> + /// </summary> + public double HectousGallons => As(VolumeUnit.HectousGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.ImperialBeerBarrel"/> + /// </summary> + public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.ImperialGallon"/> + /// </summary> + public double ImperialGallons => As(VolumeUnit.ImperialGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.ImperialOunce"/> + /// </summary> + public double ImperialOunces => As(VolumeUnit.ImperialOunce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.ImperialPint"/> + /// </summary> + public double ImperialPints => As(VolumeUnit.ImperialPint); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.KilocubicFoot"/> + /// </summary> + public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.KilocubicMeter"/> + /// </summary> + public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.KiloimperialGallon"/> + /// </summary> + public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Kiloliter"/> + /// </summary> + public double Kiloliters => As(VolumeUnit.Kiloliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.KilousGallon"/> + /// </summary> + public double KilousGallons => As(VolumeUnit.KilousGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Liter"/> + /// </summary> + public double Liters => As(VolumeUnit.Liter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.MegacubicFoot"/> + /// </summary> + public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.MegaimperialGallon"/> + /// </summary> + public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Megaliter"/> + /// </summary> + public double Megaliters => As(VolumeUnit.Megaliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.MegausGallon"/> + /// </summary> + public double MegausGallons => As(VolumeUnit.MegausGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.MetricCup"/> + /// </summary> + public double MetricCups => As(VolumeUnit.MetricCup); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.MetricTeaspoon"/> + /// </summary> + public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Microliter"/> + /// </summary> + public double Microliters => As(VolumeUnit.Microliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Milliliter"/> + /// </summary> + public double Milliliters => As(VolumeUnit.Milliliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.Nanoliter"/> + /// </summary> + public double Nanoliters => As(VolumeUnit.Nanoliter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.OilBarrel"/> + /// </summary> + public double OilBarrels => As(VolumeUnit.OilBarrel); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UkTablespoon"/> + /// </summary> + public double UkTablespoons => As(VolumeUnit.UkTablespoon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsBeerBarrel"/> + /// </summary> + public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsCustomaryCup"/> + /// </summary> + public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsGallon"/> + /// </summary> + public double UsGallons => As(VolumeUnit.UsGallon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsLegalCup"/> + /// </summary> + public double UsLegalCups => As(VolumeUnit.UsLegalCup); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsOunce"/> + /// </summary> + public double UsOunces => As(VolumeUnit.UsOunce); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsPint"/> + /// </summary> + public double UsPints => As(VolumeUnit.UsPint); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsQuart"/> + /// </summary> + public double UsQuarts => As(VolumeUnit.UsQuart); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsTablespoon"/> + /// </summary> + public double UsTablespoons => As(VolumeUnit.UsTablespoon); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeUnit.UsTeaspoon"/> + /// </summary> + public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VolumeUnit -> BaseUnit + unitConverter.SetConversionFunction<Volume>(VolumeUnit.AcreFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.AuTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.BoardFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Centiliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicCentimeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicDecimeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicHectometer, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicInch, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicKilometer, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMicrometer, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMile, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMillimeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicYard, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Decaliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.DecausGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Deciliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.DeciusGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.HectocubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.HectocubicMeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Hectoliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.HectousGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.ImperialBeerBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.ImperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.ImperialOunce, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.ImperialPint, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.KilocubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.KilocubicMeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.KiloimperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Kiloliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.KilousGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Liter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.MegacubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.MegaimperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Megaliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.MegausGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.MetricCup, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.MetricTeaspoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Microliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Milliliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.Nanoliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.OilBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UkTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsBeerBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsCustomaryCup, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsLegalCup, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsOunce, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsPint, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsQuart, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.UsTeaspoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> VolumeUnit + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.AcreFoot, quantity => quantity.ToUnit(VolumeUnit.AcreFoot)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.AuTablespoon, quantity => quantity.ToUnit(VolumeUnit.AuTablespoon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.BoardFoot, quantity => quantity.ToUnit(VolumeUnit.BoardFoot)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Centiliter, quantity => quantity.ToUnit(VolumeUnit.Centiliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicCentimeter, quantity => quantity.ToUnit(VolumeUnit.CubicCentimeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicDecimeter, quantity => quantity.ToUnit(VolumeUnit.CubicDecimeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicFoot, quantity => quantity.ToUnit(VolumeUnit.CubicFoot)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicHectometer, quantity => quantity.ToUnit(VolumeUnit.CubicHectometer)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicInch, quantity => quantity.ToUnit(VolumeUnit.CubicInch)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicKilometer, quantity => quantity.ToUnit(VolumeUnit.CubicKilometer)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicMicrometer, quantity => quantity.ToUnit(VolumeUnit.CubicMicrometer)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicMile, quantity => quantity.ToUnit(VolumeUnit.CubicMile)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicMillimeter, quantity => quantity.ToUnit(VolumeUnit.CubicMillimeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.CubicYard, quantity => quantity.ToUnit(VolumeUnit.CubicYard)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Decaliter, quantity => quantity.ToUnit(VolumeUnit.Decaliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.DecausGallon, quantity => quantity.ToUnit(VolumeUnit.DecausGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Deciliter, quantity => quantity.ToUnit(VolumeUnit.Deciliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.DeciusGallon, quantity => quantity.ToUnit(VolumeUnit.DeciusGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.HectocubicFoot, quantity => quantity.ToUnit(VolumeUnit.HectocubicFoot)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.HectocubicMeter, quantity => quantity.ToUnit(VolumeUnit.HectocubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Hectoliter, quantity => quantity.ToUnit(VolumeUnit.Hectoliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.HectousGallon, quantity => quantity.ToUnit(VolumeUnit.HectousGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.ImperialBeerBarrel, quantity => quantity.ToUnit(VolumeUnit.ImperialBeerBarrel)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.ImperialGallon, quantity => quantity.ToUnit(VolumeUnit.ImperialGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.ImperialOunce, quantity => quantity.ToUnit(VolumeUnit.ImperialOunce)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.ImperialPint, quantity => quantity.ToUnit(VolumeUnit.ImperialPint)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.KilocubicFoot, quantity => quantity.ToUnit(VolumeUnit.KilocubicFoot)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.KilocubicMeter, quantity => quantity.ToUnit(VolumeUnit.KilocubicMeter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.KiloimperialGallon, quantity => quantity.ToUnit(VolumeUnit.KiloimperialGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Kiloliter, quantity => quantity.ToUnit(VolumeUnit.Kiloliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.KilousGallon, quantity => quantity.ToUnit(VolumeUnit.KilousGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Liter, quantity => quantity.ToUnit(VolumeUnit.Liter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.MegacubicFoot, quantity => quantity.ToUnit(VolumeUnit.MegacubicFoot)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.MegaimperialGallon, quantity => quantity.ToUnit(VolumeUnit.MegaimperialGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Megaliter, quantity => quantity.ToUnit(VolumeUnit.Megaliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.MegausGallon, quantity => quantity.ToUnit(VolumeUnit.MegausGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.MetricCup, quantity => quantity.ToUnit(VolumeUnit.MetricCup)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.MetricTeaspoon, quantity => quantity.ToUnit(VolumeUnit.MetricTeaspoon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Microliter, quantity => quantity.ToUnit(VolumeUnit.Microliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Milliliter, quantity => quantity.ToUnit(VolumeUnit.Milliliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.Nanoliter, quantity => quantity.ToUnit(VolumeUnit.Nanoliter)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.OilBarrel, quantity => quantity.ToUnit(VolumeUnit.OilBarrel)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UkTablespoon, quantity => quantity.ToUnit(VolumeUnit.UkTablespoon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsBeerBarrel, quantity => quantity.ToUnit(VolumeUnit.UsBeerBarrel)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsCustomaryCup, quantity => quantity.ToUnit(VolumeUnit.UsCustomaryCup)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsGallon, quantity => quantity.ToUnit(VolumeUnit.UsGallon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsLegalCup, quantity => quantity.ToUnit(VolumeUnit.UsLegalCup)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsOunce, quantity => quantity.ToUnit(VolumeUnit.UsOunce)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsPint, quantity => quantity.ToUnit(VolumeUnit.UsPint)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsQuart, quantity => quantity.ToUnit(VolumeUnit.UsQuart)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsTablespoon, quantity => quantity.ToUnit(VolumeUnit.UsTablespoon)); + unitConverter.SetConversionFunction<Volume>(VolumeUnit.CubicMeter, VolumeUnit.UsTeaspoon, quantity => quantity.ToUnit(VolumeUnit.UsTeaspoon)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.AcreFoot, new CultureInfo("en-US"), false, true, new string[]{"ac-ft", "acre-foot", "acre-feet"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.AuTablespoon, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.AuTablespoon, new CultureInfo("ru-RU"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.AuTablespoon, new CultureInfo("nb-NO"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.BoardFoot, new CultureInfo("en-US"), false, true, new string[]{"bf", "board foot", "board feet"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.BoardFoot, new CultureInfo("fr-CA"), false, true, new string[]{"pmp", "pied-planche", "pied de planche"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Centiliter, new CultureInfo("en-US"), false, true, new string[]{"cl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Centiliter, new CultureInfo("ru-RU"), false, true, new string[]{"сл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicCentimeter, new CultureInfo("en-US"), false, true, new string[]{"cm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicCentimeter, new CultureInfo("ru-RU"), false, true, new string[]{"см³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicDecimeter, new CultureInfo("en-US"), false, true, new string[]{"dm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicDecimeter, new CultureInfo("ru-RU"), false, true, new string[]{"дм³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicFoot, new CultureInfo("en-US"), false, true, new string[]{"ft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicFoot, new CultureInfo("ru-RU"), false, true, new string[]{"фут³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicHectometer, new CultureInfo("en-US"), false, true, new string[]{"hm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicHectometer, new CultureInfo("ru-RU"), false, true, new string[]{"гм³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicInch, new CultureInfo("en-US"), false, true, new string[]{"in³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicInch, new CultureInfo("ru-RU"), false, true, new string[]{"дюйм³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicKilometer, new CultureInfo("en-US"), false, true, new string[]{"km³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicKilometer, new CultureInfo("ru-RU"), false, true, new string[]{"км³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMeter, new CultureInfo("en-US"), false, true, new string[]{"m³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"м³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMicrometer, new CultureInfo("en-US"), false, true, new string[]{"µm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMicrometer, new CultureInfo("ru-RU"), false, true, new string[]{"мкм³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMile, new CultureInfo("en-US"), false, true, new string[]{"mi³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMile, new CultureInfo("ru-RU"), false, true, new string[]{"миля³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMillimeter, new CultureInfo("en-US"), false, true, new string[]{"mm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicMillimeter, new CultureInfo("ru-RU"), false, true, new string[]{"мм³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicYard, new CultureInfo("en-US"), false, true, new string[]{"yd³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.CubicYard, new CultureInfo("ru-RU"), false, true, new string[]{"ярд³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Decaliter, new CultureInfo("en-US"), false, true, new string[]{"dal"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Decaliter, new CultureInfo("ru-RU"), false, true, new string[]{"дал"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.DecausGallon, new CultureInfo("en-US"), false, true, new string[]{"dagal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.DecausGallon, new CultureInfo("ru-RU"), false, true, new string[]{"даАмериканский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Deciliter, new CultureInfo("en-US"), false, true, new string[]{"dl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Deciliter, new CultureInfo("ru-RU"), false, true, new string[]{"дл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.DeciusGallon, new CultureInfo("en-US"), false, true, new string[]{"dgal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.DeciusGallon, new CultureInfo("ru-RU"), false, true, new string[]{"дАмериканский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.HectocubicFoot, new CultureInfo("en-US"), false, true, new string[]{"hft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.HectocubicFoot, new CultureInfo("ru-RU"), false, true, new string[]{"гфут³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.HectocubicMeter, new CultureInfo("en-US"), false, true, new string[]{"hm³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.HectocubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"гм³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Hectoliter, new CultureInfo("en-US"), false, true, new string[]{"hl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Hectoliter, new CultureInfo("ru-RU"), false, true, new string[]{"гл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.HectousGallon, new CultureInfo("en-US"), false, true, new string[]{"hgal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.HectousGallon, new CultureInfo("ru-RU"), false, true, new string[]{"гАмериканский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.ImperialBeerBarrel, new CultureInfo("en-US"), false, true, new string[]{"bl (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.ImperialGallon, new CultureInfo("en-US"), false, true, new string[]{"gal (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.ImperialGallon, new CultureInfo("ru-RU"), false, true, new string[]{"Английский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.ImperialOunce, new CultureInfo("en-US"), false, true, new string[]{"oz (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.ImperialOunce, new CultureInfo("ru-RU"), false, true, new string[]{"Английская унция"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.ImperialPint, new CultureInfo("en-US"), false, true, new string[]{"pt (imp.)", "UK pt", "pt", "p"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KilocubicFoot, new CultureInfo("en-US"), false, true, new string[]{"kft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KilocubicFoot, new CultureInfo("ru-RU"), false, true, new string[]{"кфут³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KilocubicMeter, new CultureInfo("en-US"), false, true, new string[]{"km³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KilocubicMeter, new CultureInfo("ru-RU"), false, true, new string[]{"км³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KiloimperialGallon, new CultureInfo("en-US"), false, true, new string[]{"kgal (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KiloimperialGallon, new CultureInfo("ru-RU"), false, true, new string[]{"кАнглийский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Kiloliter, new CultureInfo("en-US"), false, true, new string[]{"kl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Kiloliter, new CultureInfo("ru-RU"), false, true, new string[]{"кл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KilousGallon, new CultureInfo("en-US"), false, true, new string[]{"kgal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.KilousGallon, new CultureInfo("ru-RU"), false, true, new string[]{"кАмериканский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Liter, new CultureInfo("en-US"), false, true, new string[]{"l"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Liter, new CultureInfo("ru-RU"), false, true, new string[]{"л"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MegacubicFoot, new CultureInfo("en-US"), false, true, new string[]{"Mft³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MegacubicFoot, new CultureInfo("ru-RU"), false, true, new string[]{"Мфут³"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MegaimperialGallon, new CultureInfo("en-US"), false, true, new string[]{"Mgal (imp.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MegaimperialGallon, new CultureInfo("ru-RU"), false, true, new string[]{"МАнглийский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Megaliter, new CultureInfo("en-US"), false, true, new string[]{"Ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Megaliter, new CultureInfo("ru-RU"), false, true, new string[]{"Мл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MegausGallon, new CultureInfo("en-US"), false, true, new string[]{"Mgal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MegausGallon, new CultureInfo("ru-RU"), false, true, new string[]{"МАмериканский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MetricCup, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MetricTeaspoon, new CultureInfo("en-US"), false, true, new string[]{"tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MetricTeaspoon, new CultureInfo("ru-RU"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.MetricTeaspoon, new CultureInfo("nb-NO"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Microliter, new CultureInfo("en-US"), false, true, new string[]{"µl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Microliter, new CultureInfo("ru-RU"), false, true, new string[]{"мкл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Milliliter, new CultureInfo("en-US"), false, true, new string[]{"ml"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Milliliter, new CultureInfo("ru-RU"), false, true, new string[]{"мл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Nanoliter, new CultureInfo("en-US"), false, true, new string[]{"nl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.Nanoliter, new CultureInfo("ru-RU"), false, true, new string[]{"нл"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.OilBarrel, new CultureInfo("en-US"), false, true, new string[]{"bbl"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UkTablespoon, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UkTablespoon, new CultureInfo("ru-RU"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UkTablespoon, new CultureInfo("nb-NO"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsBeerBarrel, new CultureInfo("en-US"), false, true, new string[]{"bl (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsCustomaryCup, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsGallon, new CultureInfo("en-US"), false, true, new string[]{"gal (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsGallon, new CultureInfo("ru-RU"), false, true, new string[]{"Американский галлон"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsLegalCup, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsOunce, new CultureInfo("en-US"), false, true, new string[]{"oz (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsOunce, new CultureInfo("ru-RU"), false, true, new string[]{"Американская унция"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsPint, new CultureInfo("en-US"), false, true, new string[]{"pt (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsQuart, new CultureInfo("en-US"), false, true, new string[]{"qt (U.S.)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsTablespoon, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsTablespoon, new CultureInfo("ru-RU"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsTablespoon, new CultureInfo("nb-NO"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsTeaspoon, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsTeaspoon, new CultureInfo("ru-RU"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeUnit.UsTeaspoon, new CultureInfo("nb-NO"), false, true, new string[]{""}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VolumeUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VolumeUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.AcreFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromAcreFeet(QuantityValue acrefeet) + { + double value = (double) acrefeet; + return new Volume(value, VolumeUnit.AcreFoot); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.AuTablespoon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromAuTablespoons(QuantityValue autablespoons) + { + double value = (double) autablespoons; + return new Volume(value, VolumeUnit.AuTablespoon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.BoardFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromBoardFeet(QuantityValue boardfeet) + { + double value = (double) boardfeet; + return new Volume(value, VolumeUnit.BoardFoot); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Centiliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCentiliters(QuantityValue centiliters) + { + double value = (double) centiliters; + return new Volume(value, VolumeUnit.Centiliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicCentimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) + { + double value = (double) cubiccentimeters; + return new Volume(value, VolumeUnit.CubicCentimeter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicDecimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) + { + double value = (double) cubicdecimeters; + return new Volume(value, VolumeUnit.CubicDecimeter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicFeet(QuantityValue cubicfeet) + { + double value = (double) cubicfeet; + return new Volume(value, VolumeUnit.CubicFoot); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicHectometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicHectometers(QuantityValue cubichectometers) + { + double value = (double) cubichectometers; + return new Volume(value, VolumeUnit.CubicHectometer); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicInch"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicInches(QuantityValue cubicinches) + { + double value = (double) cubicinches; + return new Volume(value, VolumeUnit.CubicInch); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicKilometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicKilometers(QuantityValue cubickilometers) + { + double value = (double) cubickilometers; + return new Volume(value, VolumeUnit.CubicKilometer); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicMeters(QuantityValue cubicmeters) + { + double value = (double) cubicmeters; + return new Volume(value, VolumeUnit.CubicMeter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicMicrometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) + { + double value = (double) cubicmicrometers; + return new Volume(value, VolumeUnit.CubicMicrometer); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicMile"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicMiles(QuantityValue cubicmiles) + { + double value = (double) cubicmiles; + return new Volume(value, VolumeUnit.CubicMile); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) + { + double value = (double) cubicmillimeters; + return new Volume(value, VolumeUnit.CubicMillimeter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.CubicYard"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromCubicYards(QuantityValue cubicyards) + { + double value = (double) cubicyards; + return new Volume(value, VolumeUnit.CubicYard); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Decaliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromDecaliters(QuantityValue decaliters) + { + double value = (double) decaliters; + return new Volume(value, VolumeUnit.Decaliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.DecausGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromDecausGallons(QuantityValue decausgallons) + { + double value = (double) decausgallons; + return new Volume(value, VolumeUnit.DecausGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Deciliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromDeciliters(QuantityValue deciliters) + { + double value = (double) deciliters; + return new Volume(value, VolumeUnit.Deciliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.DeciusGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromDeciusGallons(QuantityValue deciusgallons) + { + double value = (double) deciusgallons; + return new Volume(value, VolumeUnit.DeciusGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.HectocubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) + { + double value = (double) hectocubicfeet; + return new Volume(value, VolumeUnit.HectocubicFoot); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.HectocubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) + { + double value = (double) hectocubicmeters; + return new Volume(value, VolumeUnit.HectocubicMeter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Hectoliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromHectoliters(QuantityValue hectoliters) + { + double value = (double) hectoliters; + return new Volume(value, VolumeUnit.Hectoliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.HectousGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromHectousGallons(QuantityValue hectousgallons) + { + double value = (double) hectousgallons; + return new Volume(value, VolumeUnit.HectousGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.ImperialBeerBarrel"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) + { + double value = (double) imperialbeerbarrels; + return new Volume(value, VolumeUnit.ImperialBeerBarrel); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.ImperialGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromImperialGallons(QuantityValue imperialgallons) + { + double value = (double) imperialgallons; + return new Volume(value, VolumeUnit.ImperialGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.ImperialOunce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromImperialOunces(QuantityValue imperialounces) + { + double value = (double) imperialounces; + return new Volume(value, VolumeUnit.ImperialOunce); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.ImperialPint"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromImperialPints(QuantityValue imperialpints) + { + double value = (double) imperialpints; + return new Volume(value, VolumeUnit.ImperialPint); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.KilocubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) + { + double value = (double) kilocubicfeet; + return new Volume(value, VolumeUnit.KilocubicFoot); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.KilocubicMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) + { + double value = (double) kilocubicmeters; + return new Volume(value, VolumeUnit.KilocubicMeter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.KiloimperialGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) + { + double value = (double) kiloimperialgallons; + return new Volume(value, VolumeUnit.KiloimperialGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Kiloliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromKiloliters(QuantityValue kiloliters) + { + double value = (double) kiloliters; + return new Volume(value, VolumeUnit.Kiloliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.KilousGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromKilousGallons(QuantityValue kilousgallons) + { + double value = (double) kilousgallons; + return new Volume(value, VolumeUnit.KilousGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Liter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromLiters(QuantityValue liters) + { + double value = (double) liters; + return new Volume(value, VolumeUnit.Liter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.MegacubicFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) + { + double value = (double) megacubicfeet; + return new Volume(value, VolumeUnit.MegacubicFoot); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.MegaimperialGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) + { + double value = (double) megaimperialgallons; + return new Volume(value, VolumeUnit.MegaimperialGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Megaliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMegaliters(QuantityValue megaliters) + { + double value = (double) megaliters; + return new Volume(value, VolumeUnit.Megaliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.MegausGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMegausGallons(QuantityValue megausgallons) + { + double value = (double) megausgallons; + return new Volume(value, VolumeUnit.MegausGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.MetricCup"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMetricCups(QuantityValue metriccups) + { + double value = (double) metriccups; + return new Volume(value, VolumeUnit.MetricCup); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.MetricTeaspoon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) + { + double value = (double) metricteaspoons; + return new Volume(value, VolumeUnit.MetricTeaspoon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Microliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMicroliters(QuantityValue microliters) + { + double value = (double) microliters; + return new Volume(value, VolumeUnit.Microliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Milliliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromMilliliters(QuantityValue milliliters) + { + double value = (double) milliliters; + return new Volume(value, VolumeUnit.Milliliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.Nanoliter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromNanoliters(QuantityValue nanoliters) + { + double value = (double) nanoliters; + return new Volume(value, VolumeUnit.Nanoliter); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.OilBarrel"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromOilBarrels(QuantityValue oilbarrels) + { + double value = (double) oilbarrels; + return new Volume(value, VolumeUnit.OilBarrel); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UkTablespoon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUkTablespoons(QuantityValue uktablespoons) + { + double value = (double) uktablespoons; + return new Volume(value, VolumeUnit.UkTablespoon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsBeerBarrel"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) + { + double value = (double) usbeerbarrels; + return new Volume(value, VolumeUnit.UsBeerBarrel); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsCustomaryCup"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) + { + double value = (double) uscustomarycups; + return new Volume(value, VolumeUnit.UsCustomaryCup); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsGallon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsGallons(QuantityValue usgallons) + { + double value = (double) usgallons; + return new Volume(value, VolumeUnit.UsGallon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsLegalCup"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsLegalCups(QuantityValue uslegalcups) + { + double value = (double) uslegalcups; + return new Volume(value, VolumeUnit.UsLegalCup); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsOunce"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsOunces(QuantityValue usounces) + { + double value = (double) usounces; + return new Volume(value, VolumeUnit.UsOunce); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsPint"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsPints(QuantityValue uspints) + { + double value = (double) uspints; + return new Volume(value, VolumeUnit.UsPint); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsQuart"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsQuarts(QuantityValue usquarts) + { + double value = (double) usquarts; + return new Volume(value, VolumeUnit.UsQuart); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsTablespoon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsTablespoons(QuantityValue ustablespoons) + { + double value = (double) ustablespoons; + return new Volume(value, VolumeUnit.UsTablespoon); + } + + /// <summary> + /// Creates a <see cref="Volume"/> from <see cref="VolumeUnit.UsTeaspoon"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static Volume FromUsTeaspoons(QuantityValue usteaspoons) + { + double value = (double) usteaspoons; + return new Volume(value, VolumeUnit.UsTeaspoon); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VolumeUnit" /> to <see cref="Volume" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>Volume unit value.</returns> + public static Volume From(QuantityValue value, VolumeUnit fromUnit) + { + return new Volume((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static Volume Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static Volume Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<Volume, VolumeUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out Volume result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out Volume result) + { + return QuantityParser.Default.TryParse<Volume, VolumeUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VolumeUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VolumeUnit)"/> + public static bool TryParseUnit(string str, out VolumeUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeUnit unit) + { + return UnitParser.Default.TryParse<VolumeUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static Volume operator -(Volume right) + { + return new Volume(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="Volume"/> from adding two <see cref="Volume"/>.</summary> + public static Volume operator +(Volume left, Volume right) + { + return new Volume(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Volume"/> from subtracting two <see cref="Volume"/>.</summary> + public static Volume operator -(Volume left, Volume right) + { + return new Volume(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="Volume"/> from multiplying value and <see cref="Volume"/>.</summary> + public static Volume operator *(double left, Volume right) + { + return new Volume(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="Volume"/> from multiplying value and <see cref="Volume"/>.</summary> + public static Volume operator *(Volume left, double right) + { + return new Volume(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="Volume"/> from dividing <see cref="Volume"/> by value.</summary> + public static Volume operator /(Volume left, double right) + { + return new Volume(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="Volume"/> by <see cref="Volume"/>.</summary> + public static double operator /(Volume left, Volume right) + { + return left.CubicMeters / right.CubicMeters; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(Volume left, Volume right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(Volume left, Volume right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(Volume left, Volume right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(Volume left, Volume right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="Volume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Volume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(Volume left, Volume right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="Volume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Volume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(Volume left, Volume right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Volume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Volume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is Volume otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="Volume"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(Volume, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(Volume other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="Volume"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is Volume otherQuantity)) throw new ArgumentException("Expected type Volume.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="Volume"/> with another <see cref="Volume"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(Volume other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another Volume within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current Volume.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VolumeUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VolumeUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this Volume to another Volume with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A Volume with the specified unit.</returns> + public Volume ToUnit(VolumeUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="Volume"/> to another <see cref="Volume"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A Volume with the specified unit.</returns> + public Volume ToUnit(VolumeUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(Volume), Unit, typeof(Volume), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Volume)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="Volume"/> to another <see cref="Volume"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="Volume"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VolumeUnit unit, [NotNullWhen(true)] out Volume? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Volume? convertedOrNull = (Unit, unit) switch + { + // VolumeUnit -> BaseUnit + (VolumeUnit.AcreFoot, VolumeUnit.CubicMeter) => new Volume(_value / 0.000810714, VolumeUnit.CubicMeter), + (VolumeUnit.AuTablespoon, VolumeUnit.CubicMeter) => new Volume(_value * 2e-5, VolumeUnit.CubicMeter), + (VolumeUnit.BoardFoot, VolumeUnit.CubicMeter) => new Volume(_value * 2.3597372158e-3, VolumeUnit.CubicMeter), + (VolumeUnit.Centiliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-2d, VolumeUnit.CubicMeter), + (VolumeUnit.CubicCentimeter, VolumeUnit.CubicMeter) => new Volume(_value / 1e6, VolumeUnit.CubicMeter), + (VolumeUnit.CubicDecimeter, VolumeUnit.CubicMeter) => new Volume(_value / 1e3, VolumeUnit.CubicMeter), + (VolumeUnit.CubicFoot, VolumeUnit.CubicMeter) => new Volume(_value * 2.8316846592e-2, VolumeUnit.CubicMeter), + (VolumeUnit.CubicHectometer, VolumeUnit.CubicMeter) => new Volume(_value * 1e6, VolumeUnit.CubicMeter), + (VolumeUnit.CubicInch, VolumeUnit.CubicMeter) => new Volume(_value * 1.6387 * 1e-5, VolumeUnit.CubicMeter), + (VolumeUnit.CubicKilometer, VolumeUnit.CubicMeter) => new Volume(_value * 1e9, VolumeUnit.CubicMeter), + (VolumeUnit.CubicMicrometer, VolumeUnit.CubicMeter) => new Volume(_value / 1e18, VolumeUnit.CubicMeter), + (VolumeUnit.CubicMile, VolumeUnit.CubicMeter) => new Volume(_value * 4.16818182544058e9, VolumeUnit.CubicMeter), + (VolumeUnit.CubicMillimeter, VolumeUnit.CubicMeter) => new Volume(_value / 1e9, VolumeUnit.CubicMeter), + (VolumeUnit.CubicYard, VolumeUnit.CubicMeter) => new Volume(_value * 0.764554858, VolumeUnit.CubicMeter), + (VolumeUnit.Decaliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e1d, VolumeUnit.CubicMeter), + (VolumeUnit.DecausGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00378541) * 1e1d, VolumeUnit.CubicMeter), + (VolumeUnit.Deciliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-1d, VolumeUnit.CubicMeter), + (VolumeUnit.DeciusGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00378541) * 1e-1d, VolumeUnit.CubicMeter), + (VolumeUnit.HectocubicFoot, VolumeUnit.CubicMeter) => new Volume((_value * 2.8316846592e-2) * 1e2d, VolumeUnit.CubicMeter), + (VolumeUnit.HectocubicMeter, VolumeUnit.CubicMeter) => new Volume((_value) * 1e2d, VolumeUnit.CubicMeter), + (VolumeUnit.Hectoliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e2d, VolumeUnit.CubicMeter), + (VolumeUnit.HectousGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00378541) * 1e2d, VolumeUnit.CubicMeter), + (VolumeUnit.ImperialBeerBarrel, VolumeUnit.CubicMeter) => new Volume(_value * 0.16365924, VolumeUnit.CubicMeter), + (VolumeUnit.ImperialGallon, VolumeUnit.CubicMeter) => new Volume(_value * 0.00454609000000181429905810072407, VolumeUnit.CubicMeter), + (VolumeUnit.ImperialOunce, VolumeUnit.CubicMeter) => new Volume(_value * 2.8413062499962901241875439064617e-5, VolumeUnit.CubicMeter), + (VolumeUnit.ImperialPint, VolumeUnit.CubicMeter) => new Volume(_value * 5.6826125e-4, VolumeUnit.CubicMeter), + (VolumeUnit.KilocubicFoot, VolumeUnit.CubicMeter) => new Volume((_value * 2.8316846592e-2) * 1e3d, VolumeUnit.CubicMeter), + (VolumeUnit.KilocubicMeter, VolumeUnit.CubicMeter) => new Volume((_value) * 1e3d, VolumeUnit.CubicMeter), + (VolumeUnit.KiloimperialGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00454609000000181429905810072407) * 1e3d, VolumeUnit.CubicMeter), + (VolumeUnit.Kiloliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e3d, VolumeUnit.CubicMeter), + (VolumeUnit.KilousGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00378541) * 1e3d, VolumeUnit.CubicMeter), + (VolumeUnit.Liter, VolumeUnit.CubicMeter) => new Volume(_value / 1e3, VolumeUnit.CubicMeter), + (VolumeUnit.MegacubicFoot, VolumeUnit.CubicMeter) => new Volume((_value * 2.8316846592e-2) * 1e6d, VolumeUnit.CubicMeter), + (VolumeUnit.MegaimperialGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00454609000000181429905810072407) * 1e6d, VolumeUnit.CubicMeter), + (VolumeUnit.Megaliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e6d, VolumeUnit.CubicMeter), + (VolumeUnit.MegausGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00378541) * 1e6d, VolumeUnit.CubicMeter), + (VolumeUnit.MetricCup, VolumeUnit.CubicMeter) => new Volume(_value * 0.00025, VolumeUnit.CubicMeter), + (VolumeUnit.MetricTeaspoon, VolumeUnit.CubicMeter) => new Volume(_value * 0.5e-5, VolumeUnit.CubicMeter), + (VolumeUnit.Microliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-6d, VolumeUnit.CubicMeter), + (VolumeUnit.Milliliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-3d, VolumeUnit.CubicMeter), + (VolumeUnit.Nanoliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-9d, VolumeUnit.CubicMeter), + (VolumeUnit.OilBarrel, VolumeUnit.CubicMeter) => new Volume(_value * 0.158987294928, VolumeUnit.CubicMeter), + (VolumeUnit.UkTablespoon, VolumeUnit.CubicMeter) => new Volume(_value * 1.5e-5, VolumeUnit.CubicMeter), + (VolumeUnit.UsBeerBarrel, VolumeUnit.CubicMeter) => new Volume(_value * 0.1173477658, VolumeUnit.CubicMeter), + (VolumeUnit.UsCustomaryCup, VolumeUnit.CubicMeter) => new Volume(_value * 0.0002365882365, VolumeUnit.CubicMeter), + (VolumeUnit.UsGallon, VolumeUnit.CubicMeter) => new Volume(_value * 0.00378541, VolumeUnit.CubicMeter), + (VolumeUnit.UsLegalCup, VolumeUnit.CubicMeter) => new Volume(_value * 0.00024, VolumeUnit.CubicMeter), + (VolumeUnit.UsOunce, VolumeUnit.CubicMeter) => new Volume(_value * 2.957352956253760505068307980135e-5, VolumeUnit.CubicMeter), + (VolumeUnit.UsPint, VolumeUnit.CubicMeter) => new Volume(_value * 4.73176473e-4, VolumeUnit.CubicMeter), + (VolumeUnit.UsQuart, VolumeUnit.CubicMeter) => new Volume(_value * 9.46352946e-4, VolumeUnit.CubicMeter), + (VolumeUnit.UsTablespoon, VolumeUnit.CubicMeter) => new Volume(_value * 1.478676478125e-5, VolumeUnit.CubicMeter), + (VolumeUnit.UsTeaspoon, VolumeUnit.CubicMeter) => new Volume(_value * 4.92892159375e-6, VolumeUnit.CubicMeter), + + // BaseUnit -> VolumeUnit + (VolumeUnit.CubicMeter, VolumeUnit.AcreFoot) => new Volume(_value * 0.000810714, VolumeUnit.AcreFoot), + (VolumeUnit.CubicMeter, VolumeUnit.AuTablespoon) => new Volume(_value / 2e-5, VolumeUnit.AuTablespoon), + (VolumeUnit.CubicMeter, VolumeUnit.BoardFoot) => new Volume(_value / 2.3597372158e-3, VolumeUnit.BoardFoot), + (VolumeUnit.CubicMeter, VolumeUnit.Centiliter) => new Volume((_value * 1e3) / 1e-2d, VolumeUnit.Centiliter), + (VolumeUnit.CubicMeter, VolumeUnit.CubicCentimeter) => new Volume(_value * 1e6, VolumeUnit.CubicCentimeter), + (VolumeUnit.CubicMeter, VolumeUnit.CubicDecimeter) => new Volume(_value * 1e3, VolumeUnit.CubicDecimeter), + (VolumeUnit.CubicMeter, VolumeUnit.CubicFoot) => new Volume(_value / 2.8316846592e-2, VolumeUnit.CubicFoot), + (VolumeUnit.CubicMeter, VolumeUnit.CubicHectometer) => new Volume(_value / 1e6, VolumeUnit.CubicHectometer), + (VolumeUnit.CubicMeter, VolumeUnit.CubicInch) => new Volume(_value / (1.6387 * 1e-5), VolumeUnit.CubicInch), + (VolumeUnit.CubicMeter, VolumeUnit.CubicKilometer) => new Volume(_value / 1e9, VolumeUnit.CubicKilometer), + (VolumeUnit.CubicMeter, VolumeUnit.CubicMicrometer) => new Volume(_value * 1e18, VolumeUnit.CubicMicrometer), + (VolumeUnit.CubicMeter, VolumeUnit.CubicMile) => new Volume(_value / 4.16818182544058e9, VolumeUnit.CubicMile), + (VolumeUnit.CubicMeter, VolumeUnit.CubicMillimeter) => new Volume(_value * 1e9, VolumeUnit.CubicMillimeter), + (VolumeUnit.CubicMeter, VolumeUnit.CubicYard) => new Volume(_value / 0.764554858, VolumeUnit.CubicYard), + (VolumeUnit.CubicMeter, VolumeUnit.Decaliter) => new Volume((_value * 1e3) / 1e1d, VolumeUnit.Decaliter), + (VolumeUnit.CubicMeter, VolumeUnit.DecausGallon) => new Volume((_value / 0.00378541) / 1e1d, VolumeUnit.DecausGallon), + (VolumeUnit.CubicMeter, VolumeUnit.Deciliter) => new Volume((_value * 1e3) / 1e-1d, VolumeUnit.Deciliter), + (VolumeUnit.CubicMeter, VolumeUnit.DeciusGallon) => new Volume((_value / 0.00378541) / 1e-1d, VolumeUnit.DeciusGallon), + (VolumeUnit.CubicMeter, VolumeUnit.HectocubicFoot) => new Volume((_value / 2.8316846592e-2) / 1e2d, VolumeUnit.HectocubicFoot), + (VolumeUnit.CubicMeter, VolumeUnit.HectocubicMeter) => new Volume((_value) / 1e2d, VolumeUnit.HectocubicMeter), + (VolumeUnit.CubicMeter, VolumeUnit.Hectoliter) => new Volume((_value * 1e3) / 1e2d, VolumeUnit.Hectoliter), + (VolumeUnit.CubicMeter, VolumeUnit.HectousGallon) => new Volume((_value / 0.00378541) / 1e2d, VolumeUnit.HectousGallon), + (VolumeUnit.CubicMeter, VolumeUnit.ImperialBeerBarrel) => new Volume(_value / 0.16365924, VolumeUnit.ImperialBeerBarrel), + (VolumeUnit.CubicMeter, VolumeUnit.ImperialGallon) => new Volume(_value / 0.00454609000000181429905810072407, VolumeUnit.ImperialGallon), + (VolumeUnit.CubicMeter, VolumeUnit.ImperialOunce) => new Volume(_value / 2.8413062499962901241875439064617e-5, VolumeUnit.ImperialOunce), + (VolumeUnit.CubicMeter, VolumeUnit.ImperialPint) => new Volume(_value / 5.6826125e-4, VolumeUnit.ImperialPint), + (VolumeUnit.CubicMeter, VolumeUnit.KilocubicFoot) => new Volume((_value / 2.8316846592e-2) / 1e3d, VolumeUnit.KilocubicFoot), + (VolumeUnit.CubicMeter, VolumeUnit.KilocubicMeter) => new Volume((_value) / 1e3d, VolumeUnit.KilocubicMeter), + (VolumeUnit.CubicMeter, VolumeUnit.KiloimperialGallon) => new Volume((_value / 0.00454609000000181429905810072407) / 1e3d, VolumeUnit.KiloimperialGallon), + (VolumeUnit.CubicMeter, VolumeUnit.Kiloliter) => new Volume((_value * 1e3) / 1e3d, VolumeUnit.Kiloliter), + (VolumeUnit.CubicMeter, VolumeUnit.KilousGallon) => new Volume((_value / 0.00378541) / 1e3d, VolumeUnit.KilousGallon), + (VolumeUnit.CubicMeter, VolumeUnit.Liter) => new Volume(_value * 1e3, VolumeUnit.Liter), + (VolumeUnit.CubicMeter, VolumeUnit.MegacubicFoot) => new Volume((_value / 2.8316846592e-2) / 1e6d, VolumeUnit.MegacubicFoot), + (VolumeUnit.CubicMeter, VolumeUnit.MegaimperialGallon) => new Volume((_value / 0.00454609000000181429905810072407) / 1e6d, VolumeUnit.MegaimperialGallon), + (VolumeUnit.CubicMeter, VolumeUnit.Megaliter) => new Volume((_value * 1e3) / 1e6d, VolumeUnit.Megaliter), + (VolumeUnit.CubicMeter, VolumeUnit.MegausGallon) => new Volume((_value / 0.00378541) / 1e6d, VolumeUnit.MegausGallon), + (VolumeUnit.CubicMeter, VolumeUnit.MetricCup) => new Volume(_value / 0.00025, VolumeUnit.MetricCup), + (VolumeUnit.CubicMeter, VolumeUnit.MetricTeaspoon) => new Volume(_value / 0.5e-5, VolumeUnit.MetricTeaspoon), + (VolumeUnit.CubicMeter, VolumeUnit.Microliter) => new Volume((_value * 1e3) / 1e-6d, VolumeUnit.Microliter), + (VolumeUnit.CubicMeter, VolumeUnit.Milliliter) => new Volume((_value * 1e3) / 1e-3d, VolumeUnit.Milliliter), + (VolumeUnit.CubicMeter, VolumeUnit.Nanoliter) => new Volume((_value * 1e3) / 1e-9d, VolumeUnit.Nanoliter), + (VolumeUnit.CubicMeter, VolumeUnit.OilBarrel) => new Volume(_value / 0.158987294928, VolumeUnit.OilBarrel), + (VolumeUnit.CubicMeter, VolumeUnit.UkTablespoon) => new Volume(_value / 1.5e-5, VolumeUnit.UkTablespoon), + (VolumeUnit.CubicMeter, VolumeUnit.UsBeerBarrel) => new Volume(_value / 0.1173477658, VolumeUnit.UsBeerBarrel), + (VolumeUnit.CubicMeter, VolumeUnit.UsCustomaryCup) => new Volume(_value / 0.0002365882365, VolumeUnit.UsCustomaryCup), + (VolumeUnit.CubicMeter, VolumeUnit.UsGallon) => new Volume(_value / 0.00378541, VolumeUnit.UsGallon), + (VolumeUnit.CubicMeter, VolumeUnit.UsLegalCup) => new Volume(_value / 0.00024, VolumeUnit.UsLegalCup), + (VolumeUnit.CubicMeter, VolumeUnit.UsOunce) => new Volume(_value / 2.957352956253760505068307980135e-5, VolumeUnit.UsOunce), + (VolumeUnit.CubicMeter, VolumeUnit.UsPint) => new Volume(_value / 4.73176473e-4, VolumeUnit.UsPint), + (VolumeUnit.CubicMeter, VolumeUnit.UsQuart) => new Volume(_value / 9.46352946e-4, VolumeUnit.UsQuart), + (VolumeUnit.CubicMeter, VolumeUnit.UsTablespoon) => new Volume(_value / 1.478676478125e-5, VolumeUnit.UsTablespoon), + (VolumeUnit.CubicMeter, VolumeUnit.UsTeaspoon) => new Volume(_value / 4.92892159375e-6, VolumeUnit.UsTeaspoon), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VolumeUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VolumeUnit> IQuantity<VolumeUnit>.ToUnit(VolumeUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VolumeUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Volume)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Volume)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(Volume)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(Volume)) + return this; + else if (conversionType == typeof(VolumeUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return Volume.Info; + else if (conversionType == typeof(BaseDimensions)) + return Volume.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(Volume)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/Volume/VolumeUnit.g.cs b/UnitsNet.Modular/GeneratedCode/Volume/VolumeUnit.g.cs new file mode 100644 index 0000000000..ec893612ac --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/Volume/VolumeUnit.g.cs @@ -0,0 +1,84 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VolumeUnit + { + AcreFoot = 1, + AuTablespoon = 2, + BoardFoot = 3, + Centiliter = 4, + CubicCentimeter = 5, + CubicDecimeter = 6, + CubicFoot = 7, + CubicHectometer = 8, + CubicInch = 9, + CubicKilometer = 10, + CubicMeter = 11, + CubicMicrometer = 12, + CubicMile = 13, + CubicMillimeter = 14, + CubicYard = 15, + Decaliter = 16, + DecausGallon = 17, + Deciliter = 18, + DeciusGallon = 19, + HectocubicFoot = 20, + HectocubicMeter = 21, + Hectoliter = 22, + HectousGallon = 23, + ImperialBeerBarrel = 24, + ImperialGallon = 25, + ImperialOunce = 26, + ImperialPint = 27, + KilocubicFoot = 28, + KilocubicMeter = 29, + KiloimperialGallon = 30, + Kiloliter = 31, + KilousGallon = 32, + Liter = 33, + MegacubicFoot = 34, + MegaimperialGallon = 35, + Megaliter = 36, + MegausGallon = 37, + MetricCup = 38, + MetricTeaspoon = 39, + Microliter = 40, + Milliliter = 41, + Nanoliter = 53, + OilBarrel = 42, + UkTablespoon = 43, + UsBeerBarrel = 44, + UsCustomaryCup = 45, + UsGallon = 46, + UsLegalCup = 47, + UsOunce = 48, + UsPint = 49, + UsQuart = 50, + UsTablespoon = 51, + UsTeaspoon = 52, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentration.csproj b/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentration.csproj new file mode 100644 index 0000000000..8a0b8643ed --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentration.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET VolumeConcentration</Title> + <Description>Adds VolumeConcentration units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>volumeconcentration unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{4aa72022-0946-6a28-a4e9-6c9add5caef6}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.VolumeConcentration</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentration.g.cs b/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentration.g.cs new file mode 100644 index 0000000000..05508af91b --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentration.g.cs @@ -0,0 +1,1240 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The volume concentration (not to be confused with volume fraction) is defined as the volume of a constituent divided by the total volume of the mixture. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Concentration#Volume_concentration + /// </remarks> + [DataContract] + public readonly partial struct VolumeConcentration : IArithmeticQuantity<VolumeConcentration, VolumeConcentrationUnit, double>, IEquatable<VolumeConcentration>, IComparable, IComparable<VolumeConcentration>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VolumeConcentrationUnit? _unit; + + static VolumeConcentration() + { + BaseDimensions = BaseDimensions.Dimensionless; + BaseUnit = VolumeConcentrationUnit.DecimalFraction; + Units = Enum.GetValues(typeof(VolumeConcentrationUnit)).Cast<VolumeConcentrationUnit>().ToArray(); + Zero = new VolumeConcentration(0, BaseUnit); + Info = new QuantityInfo<VolumeConcentrationUnit>("VolumeConcentration", + new UnitInfo<VolumeConcentrationUnit>[] + { + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.CentilitersPerLiter, "CentilitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.CentilitersPerMililiter, "CentilitersPerMililiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.DecilitersPerLiter, "DecilitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.DecilitersPerMililiter, "DecilitersPerMililiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.DecimalFraction, "DecimalFractions", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.LitersPerLiter, "LitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.LitersPerMililiter, "LitersPerMililiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.MicrolitersPerLiter, "MicrolitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.MicrolitersPerMililiter, "MicrolitersPerMililiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.MillilitersPerLiter, "MillilitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.MillilitersPerMililiter, "MillilitersPerMililiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.NanolitersPerLiter, "NanolitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.NanolitersPerMililiter, "NanolitersPerMililiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.PartPerBillion, "PartsPerBillion", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.PartPerMillion, "PartsPerMillion", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.PartPerThousand, "PartsPerThousand", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.Percent, "Percent", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.PicolitersPerLiter, "PicolitersPerLiter", BaseUnits.Undefined), + new UnitInfo<VolumeConcentrationUnit>(VolumeConcentrationUnit.PicolitersPerMililiter, "PicolitersPerMililiter", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public VolumeConcentration(double value, VolumeConcentrationUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="VolumeConcentration" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VolumeConcentrationUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of VolumeConcentration, which is DecimalFraction. All conversions go via this value. + /// </summary> + public static VolumeConcentrationUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the VolumeConcentration quantity. + /// </summary> + public static VolumeConcentrationUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. + /// </summary> + public static VolumeConcentration Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static VolumeConcentration AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VolumeConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VolumeConcentrationUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => VolumeConcentration.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.CentilitersPerLiter"/> + /// </summary> + public double CentilitersPerLiter => As(VolumeConcentrationUnit.CentilitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.CentilitersPerMililiter"/> + /// </summary> + public double CentilitersPerMililiter => As(VolumeConcentrationUnit.CentilitersPerMililiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.DecilitersPerLiter"/> + /// </summary> + public double DecilitersPerLiter => As(VolumeConcentrationUnit.DecilitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.DecilitersPerMililiter"/> + /// </summary> + public double DecilitersPerMililiter => As(VolumeConcentrationUnit.DecilitersPerMililiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.DecimalFraction"/> + /// </summary> + public double DecimalFractions => As(VolumeConcentrationUnit.DecimalFraction); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.LitersPerLiter"/> + /// </summary> + public double LitersPerLiter => As(VolumeConcentrationUnit.LitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.LitersPerMililiter"/> + /// </summary> + public double LitersPerMililiter => As(VolumeConcentrationUnit.LitersPerMililiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.MicrolitersPerLiter"/> + /// </summary> + public double MicrolitersPerLiter => As(VolumeConcentrationUnit.MicrolitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.MicrolitersPerMililiter"/> + /// </summary> + public double MicrolitersPerMililiter => As(VolumeConcentrationUnit.MicrolitersPerMililiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.MillilitersPerLiter"/> + /// </summary> + public double MillilitersPerLiter => As(VolumeConcentrationUnit.MillilitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.MillilitersPerMililiter"/> + /// </summary> + public double MillilitersPerMililiter => As(VolumeConcentrationUnit.MillilitersPerMililiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.NanolitersPerLiter"/> + /// </summary> + public double NanolitersPerLiter => As(VolumeConcentrationUnit.NanolitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.NanolitersPerMililiter"/> + /// </summary> + public double NanolitersPerMililiter => As(VolumeConcentrationUnit.NanolitersPerMililiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.PartPerBillion"/> + /// </summary> + public double PartsPerBillion => As(VolumeConcentrationUnit.PartPerBillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.PartPerMillion"/> + /// </summary> + public double PartsPerMillion => As(VolumeConcentrationUnit.PartPerMillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.PartPerThousand"/> + /// </summary> + public double PartsPerThousand => As(VolumeConcentrationUnit.PartPerThousand); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.PartPerTrillion"/> + /// </summary> + public double PartsPerTrillion => As(VolumeConcentrationUnit.PartPerTrillion); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.Percent"/> + /// </summary> + public double Percent => As(VolumeConcentrationUnit.Percent); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.PicolitersPerLiter"/> + /// </summary> + public double PicolitersPerLiter => As(VolumeConcentrationUnit.PicolitersPerLiter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeConcentrationUnit.PicolitersPerMililiter"/> + /// </summary> + public double PicolitersPerMililiter => As(VolumeConcentrationUnit.PicolitersPerMililiter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VolumeConcentrationUnit -> BaseUnit + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.CentilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.CentilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.LitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.LitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.MicrolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.MicrolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.MillilitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.MillilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.NanolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.NanolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.PartPerBillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.PartPerMillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.PartPerThousand, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.PartPerTrillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.Percent, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.PicolitersPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.PicolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecimalFraction, quantity => quantity); + + // Register in unit converter: BaseUnit -> VolumeConcentrationUnit + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.CentilitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.CentilitersPerMililiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecilitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecilitersPerMililiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.LitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.LitersPerMililiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MicrolitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MicrolitersPerMililiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MillilitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MillilitersPerMililiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.NanolitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.NanolitersPerMililiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerBillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerBillion)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerMillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerMillion)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerThousand, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerThousand)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerTrillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerTrillion)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.Percent, quantity => quantity.ToUnit(VolumeConcentrationUnit.Percent)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.PicolitersPerLiter)); + unitConverter.SetConversionFunction<VolumeConcentration>(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerMililiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.PicolitersPerMililiter)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.CentilitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"cL/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.CentilitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"cL/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.DecilitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"dL/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.DecilitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"dL/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.DecimalFraction, new CultureInfo("en-US"), false, true, new string[]{""}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.LitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"L/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.LitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"L/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.MicrolitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"µL/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.MicrolitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"µL/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.MillilitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"mL/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.MillilitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"mL/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.NanolitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"nL/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.NanolitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"nL/mL"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.PartPerBillion, new CultureInfo("en-US"), false, true, new string[]{"ppb"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.PartPerMillion, new CultureInfo("en-US"), false, true, new string[]{"ppm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.PartPerThousand, new CultureInfo("en-US"), false, true, new string[]{"‰"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.PartPerTrillion, new CultureInfo("en-US"), false, true, new string[]{"ppt"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.Percent, new CultureInfo("en-US"), false, true, new string[]{"%", "% (v/v)"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.PicolitersPerLiter, new CultureInfo("en-US"), false, true, new string[]{"pL/L"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeConcentrationUnit.PicolitersPerMililiter, new CultureInfo("en-US"), false, true, new string[]{"pL/mL"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VolumeConcentrationUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VolumeConcentrationUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.CentilitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromCentilitersPerLiter(QuantityValue centilitersperliter) + { + double value = (double) centilitersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.CentilitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.CentilitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromCentilitersPerMililiter(QuantityValue centiliterspermililiter) + { + double value = (double) centiliterspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.CentilitersPerMililiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.DecilitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromDecilitersPerLiter(QuantityValue decilitersperliter) + { + double value = (double) decilitersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.DecilitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.DecilitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromDecilitersPerMililiter(QuantityValue deciliterspermililiter) + { + double value = (double) deciliterspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.DecilitersPerMililiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.DecimalFraction"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromDecimalFractions(QuantityValue decimalfractions) + { + double value = (double) decimalfractions; + return new VolumeConcentration(value, VolumeConcentrationUnit.DecimalFraction); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.LitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromLitersPerLiter(QuantityValue litersperliter) + { + double value = (double) litersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.LitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.LitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromLitersPerMililiter(QuantityValue literspermililiter) + { + double value = (double) literspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.LitersPerMililiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.MicrolitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromMicrolitersPerLiter(QuantityValue microlitersperliter) + { + double value = (double) microlitersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.MicrolitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.MicrolitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromMicrolitersPerMililiter(QuantityValue microliterspermililiter) + { + double value = (double) microliterspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.MicrolitersPerMililiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.MillilitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromMillilitersPerLiter(QuantityValue millilitersperliter) + { + double value = (double) millilitersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.MillilitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.MillilitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromMillilitersPerMililiter(QuantityValue milliliterspermililiter) + { + double value = (double) milliliterspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.MillilitersPerMililiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.NanolitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromNanolitersPerLiter(QuantityValue nanolitersperliter) + { + double value = (double) nanolitersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.NanolitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.NanolitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromNanolitersPerMililiter(QuantityValue nanoliterspermililiter) + { + double value = (double) nanoliterspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.NanolitersPerMililiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.PartPerBillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPartsPerBillion(QuantityValue partsperbillion) + { + double value = (double) partsperbillion; + return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerBillion); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.PartPerMillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPartsPerMillion(QuantityValue partspermillion) + { + double value = (double) partspermillion; + return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerMillion); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.PartPerThousand"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPartsPerThousand(QuantityValue partsperthousand) + { + double value = (double) partsperthousand; + return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerThousand); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.PartPerTrillion"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPartsPerTrillion(QuantityValue partspertrillion) + { + double value = (double) partspertrillion; + return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerTrillion); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.Percent"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPercent(QuantityValue percent) + { + double value = (double) percent; + return new VolumeConcentration(value, VolumeConcentrationUnit.Percent); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.PicolitersPerLiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPicolitersPerLiter(QuantityValue picolitersperliter) + { + double value = (double) picolitersperliter; + return new VolumeConcentration(value, VolumeConcentrationUnit.PicolitersPerLiter); + } + + /// <summary> + /// Creates a <see cref="VolumeConcentration"/> from <see cref="VolumeConcentrationUnit.PicolitersPerMililiter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeConcentration FromPicolitersPerMililiter(QuantityValue picoliterspermililiter) + { + double value = (double) picoliterspermililiter; + return new VolumeConcentration(value, VolumeConcentrationUnit.PicolitersPerMililiter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VolumeConcentrationUnit" /> to <see cref="VolumeConcentration" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>VolumeConcentration unit value.</returns> + public static VolumeConcentration From(QuantityValue value, VolumeConcentrationUnit fromUnit) + { + return new VolumeConcentration((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static VolumeConcentration Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static VolumeConcentration Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<VolumeConcentration, VolumeConcentrationUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out VolumeConcentration result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out VolumeConcentration result) + { + return QuantityParser.Default.TryParse<VolumeConcentration, VolumeConcentrationUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeConcentrationUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeConcentrationUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VolumeConcentrationUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VolumeConcentrationUnit)"/> + public static bool TryParseUnit(string str, out VolumeConcentrationUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeConcentrationUnit unit) + { + return UnitParser.Default.TryParse<VolumeConcentrationUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static VolumeConcentration operator -(VolumeConcentration right) + { + return new VolumeConcentration(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumeConcentration"/> from adding two <see cref="VolumeConcentration"/>.</summary> + public static VolumeConcentration operator +(VolumeConcentration left, VolumeConcentration right) + { + return new VolumeConcentration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumeConcentration"/> from subtracting two <see cref="VolumeConcentration"/>.</summary> + public static VolumeConcentration operator -(VolumeConcentration left, VolumeConcentration right) + { + return new VolumeConcentration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumeConcentration"/> from multiplying value and <see cref="VolumeConcentration"/>.</summary> + public static VolumeConcentration operator *(double left, VolumeConcentration right) + { + return new VolumeConcentration(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumeConcentration"/> from multiplying value and <see cref="VolumeConcentration"/>.</summary> + public static VolumeConcentration operator *(VolumeConcentration left, double right) + { + return new VolumeConcentration(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="VolumeConcentration"/> from dividing <see cref="VolumeConcentration"/> by value.</summary> + public static VolumeConcentration operator /(VolumeConcentration left, double right) + { + return new VolumeConcentration(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="VolumeConcentration"/> by <see cref="VolumeConcentration"/>.</summary> + public static double operator /(VolumeConcentration left, VolumeConcentration right) + { + return left.DecimalFractions / right.DecimalFractions; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(VolumeConcentration left, VolumeConcentration right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(VolumeConcentration left, VolumeConcentration right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(VolumeConcentration left, VolumeConcentration right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(VolumeConcentration left, VolumeConcentration right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="VolumeConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(VolumeConcentration left, VolumeConcentration right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="VolumeConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(VolumeConcentration left, VolumeConcentration right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumeConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is VolumeConcentration otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumeConcentration"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeConcentration, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(VolumeConcentration other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="VolumeConcentration"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is VolumeConcentration otherQuantity)) throw new ArgumentException("Expected type VolumeConcentration.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="VolumeConcentration"/> with another <see cref="VolumeConcentration"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(VolumeConcentration other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another VolumeConcentration within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(VolumeConcentration other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current VolumeConcentration.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VolumeConcentrationUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VolumeConcentrationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this VolumeConcentration to another VolumeConcentration with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A VolumeConcentration with the specified unit.</returns> + public VolumeConcentration ToUnit(VolumeConcentrationUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="VolumeConcentration"/> to another <see cref="VolumeConcentration"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A VolumeConcentration with the specified unit.</returns> + public VolumeConcentration ToUnit(VolumeConcentrationUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(VolumeConcentration), Unit, typeof(VolumeConcentration), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (VolumeConcentration)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="VolumeConcentration"/> to another <see cref="VolumeConcentration"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="VolumeConcentration"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VolumeConcentrationUnit unit, [NotNullWhen(true)] out VolumeConcentration? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + VolumeConcentration? convertedOrNull = (Unit, unit) switch + { + // VolumeConcentrationUnit -> BaseUnit + (VolumeConcentrationUnit.CentilitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-2d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.CentilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-2d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.DecilitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-1d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.DecilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-1d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.LitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.LitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e-3, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.MicrolitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-6d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.MicrolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-6d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.MillilitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-3d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.MillilitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-3d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.NanolitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-9d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.NanolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-9d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.PartPerBillion, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e9, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.PartPerMillion, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e6, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.PartPerThousand, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e3, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.PartPerTrillion, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e12, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.Percent, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e2, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.PicolitersPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-12d, VolumeConcentrationUnit.DecimalFraction), + (VolumeConcentrationUnit.PicolitersPerMililiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-12d, VolumeConcentrationUnit.DecimalFraction), + + // BaseUnit -> VolumeConcentrationUnit + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerLiter) => new VolumeConcentration((_value) / 1e-2d, VolumeConcentrationUnit.CentilitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentilitersPerMililiter) => new VolumeConcentration((_value * 1e-3) / 1e-2d, VolumeConcentrationUnit.CentilitersPerMililiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerLiter) => new VolumeConcentration((_value) / 1e-1d, VolumeConcentrationUnit.DecilitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecilitersPerMililiter) => new VolumeConcentration((_value * 1e-3) / 1e-1d, VolumeConcentrationUnit.DecilitersPerMililiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerLiter) => new VolumeConcentration(_value, VolumeConcentrationUnit.LitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LitersPerMililiter) => new VolumeConcentration(_value * 1e-3, VolumeConcentrationUnit.LitersPerMililiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerLiter) => new VolumeConcentration((_value) / 1e-6d, VolumeConcentrationUnit.MicrolitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicrolitersPerMililiter) => new VolumeConcentration((_value * 1e-3) / 1e-6d, VolumeConcentrationUnit.MicrolitersPerMililiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerLiter) => new VolumeConcentration((_value) / 1e-3d, VolumeConcentrationUnit.MillilitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MillilitersPerMililiter) => new VolumeConcentration((_value * 1e-3) / 1e-3d, VolumeConcentrationUnit.MillilitersPerMililiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerLiter) => new VolumeConcentration((_value) / 1e-9d, VolumeConcentrationUnit.NanolitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanolitersPerMililiter) => new VolumeConcentration((_value * 1e-3) / 1e-9d, VolumeConcentrationUnit.NanolitersPerMililiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerBillion) => new VolumeConcentration(_value * 1e9, VolumeConcentrationUnit.PartPerBillion), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerMillion) => new VolumeConcentration(_value * 1e6, VolumeConcentrationUnit.PartPerMillion), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerThousand) => new VolumeConcentration(_value * 1e3, VolumeConcentrationUnit.PartPerThousand), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerTrillion) => new VolumeConcentration(_value * 1e12, VolumeConcentrationUnit.PartPerTrillion), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.Percent) => new VolumeConcentration(_value * 1e2, VolumeConcentrationUnit.Percent), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerLiter) => new VolumeConcentration((_value) / 1e-12d, VolumeConcentrationUnit.PicolitersPerLiter), + (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicolitersPerMililiter) => new VolumeConcentration((_value * 1e-3) / 1e-12d, VolumeConcentrationUnit.PicolitersPerMililiter), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VolumeConcentrationUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VolumeConcentrationUnit> IQuantity<VolumeConcentrationUnit>.ToUnit(VolumeConcentrationUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VolumeConcentrationUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(VolumeConcentration)) + return this; + else if (conversionType == typeof(VolumeConcentrationUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return VolumeConcentration.Info; + else if (conversionType == typeof(BaseDimensions)) + return VolumeConcentration.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentrationUnit.g.cs b/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentrationUnit.g.cs new file mode 100644 index 0000000000..b60c944f4a --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeConcentration/VolumeConcentrationUnit.g.cs @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VolumeConcentrationUnit + { + CentilitersPerLiter = 1, + CentilitersPerMililiter = 2, + DecilitersPerLiter = 3, + DecilitersPerMililiter = 4, + DecimalFraction = 5, + LitersPerLiter = 6, + LitersPerMililiter = 7, + MicrolitersPerLiter = 8, + MicrolitersPerMililiter = 9, + MillilitersPerLiter = 10, + MillilitersPerMililiter = 11, + NanolitersPerLiter = 12, + NanolitersPerMililiter = 13, + PartPerBillion = 14, + PartPerMillion = 15, + PartPerThousand = 16, + PartPerTrillion = 17, + Percent = 18, + PicolitersPerLiter = 19, + PicolitersPerMililiter = 20, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlow.csproj b/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlow.csproj new file mode 100644 index 0000000000..1254a3cdc1 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlow.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET VolumeFlow</Title> + <Description>Adds VolumeFlow units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>volumeflow unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{b22e47e1-9506-56e6-3d19-780b887d8cb3}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.VolumeFlow</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlow.g.cs b/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlow.g.cs new file mode 100644 index 0000000000..dc75ef0b59 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlow.g.cs @@ -0,0 +1,2146 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// 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. + /// </summary> + [DataContract] + public readonly partial struct VolumeFlow : IArithmeticQuantity<VolumeFlow, VolumeFlowUnit, double>, IEquatable<VolumeFlow>, IComparable, IComparable<VolumeFlow>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VolumeFlowUnit? _unit; + + static VolumeFlow() + { + BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); + BaseUnit = VolumeFlowUnit.CubicMeterPerSecond; + Units = Enum.GetValues(typeof(VolumeFlowUnit)).Cast<VolumeFlowUnit>().ToArray(); + Zero = new VolumeFlow(0, BaseUnit); + Info = new QuantityInfo<VolumeFlowUnit>("VolumeFlow", + new UnitInfo<VolumeFlowUnit>[] + { + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.AcreFootPerDay, "AcreFeetPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.AcreFootPerHour, "AcreFeetPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.AcreFootPerMinute, "AcreFeetPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.AcreFootPerSecond, "AcreFeetPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CentiliterPerDay, "CentilitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CentiliterPerHour, "CentilitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CentiliterPerMinute, "CentilitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CentiliterPerSecond, "CentilitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicCentimeterPerMinute, "CubicCentimetersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicDecimeterPerMinute, "CubicDecimetersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicFootPerHour, "CubicFeetPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicFootPerMinute, "CubicFeetPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicFootPerSecond, "CubicFeetPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicMeterPerDay, "CubicMetersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicMeterPerHour, "CubicMetersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicMeterPerMinute, "CubicMetersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicMeterPerSecond, "CubicMetersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicMillimeterPerSecond, "CubicMillimetersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicYardPerDay, "CubicYardsPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicYardPerHour, "CubicYardsPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicYardPerMinute, "CubicYardsPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.CubicYardPerSecond, "CubicYardsPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.DeciliterPerDay, "DecilitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.DeciliterPerHour, "DecilitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.DeciliterPerMinute, "DecilitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.DeciliterPerSecond, "DecilitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.KiloliterPerDay, "KilolitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.KiloliterPerHour, "KilolitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.KiloliterPerMinute, "KilolitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.KiloliterPerSecond, "KilolitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.KilousGallonPerMinute, "KilousGallonsPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.LiterPerDay, "LitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.LiterPerHour, "LitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.LiterPerMinute, "LitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.LiterPerSecond, "LitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MegaliterPerDay, "MegalitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MegaukGallonPerSecond, "MegaukGallonsPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MicroliterPerDay, "MicrolitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MicroliterPerHour, "MicrolitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MicroliterPerMinute, "MicrolitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MicroliterPerSecond, "MicrolitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MilliliterPerDay, "MillilitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MilliliterPerHour, "MillilitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MilliliterPerMinute, "MillilitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MilliliterPerSecond, "MillilitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.MillionUsGallonPerDay, "MillionUsGallonsPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.NanoliterPerDay, "NanolitersPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.NanoliterPerHour, "NanolitersPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.NanoliterPerMinute, "NanolitersPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.NanoliterPerSecond, "NanolitersPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.OilBarrelPerDay, "OilBarrelsPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.OilBarrelPerHour, "OilBarrelsPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.OilBarrelPerMinute, "OilBarrelsPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.OilBarrelPerSecond, "OilBarrelsPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UkGallonPerDay, "UkGallonsPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UkGallonPerHour, "UkGallonsPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UkGallonPerMinute, "UkGallonsPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UkGallonPerSecond, "UkGallonsPerSecond", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UsGallonPerDay, "UsGallonsPerDay", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UsGallonPerHour, "UsGallonsPerHour", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UsGallonPerMinute, "UsGallonsPerMinute", BaseUnits.Undefined), + new UnitInfo<VolumeFlowUnit>(VolumeFlowUnit.UsGallonPerSecond, "UsGallonsPerSecond", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public VolumeFlow(double value, VolumeFlowUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="VolumeFlow" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VolumeFlowUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. + /// </summary> + public static VolumeFlowUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the VolumeFlow quantity. + /// </summary> + public static VolumeFlowUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. + /// </summary> + public static VolumeFlow Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static VolumeFlow AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VolumeFlowUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.AcreFootPerDay"/> + /// </summary> + public double AcreFeetPerDay => As(VolumeFlowUnit.AcreFootPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.AcreFootPerHour"/> + /// </summary> + public double AcreFeetPerHour => As(VolumeFlowUnit.AcreFootPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.AcreFootPerMinute"/> + /// </summary> + public double AcreFeetPerMinute => As(VolumeFlowUnit.AcreFootPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.AcreFootPerSecond"/> + /// </summary> + public double AcreFeetPerSecond => As(VolumeFlowUnit.AcreFootPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CentiliterPerDay"/> + /// </summary> + public double CentilitersPerDay => As(VolumeFlowUnit.CentiliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CentiliterPerHour"/> + /// </summary> + public double CentilitersPerHour => As(VolumeFlowUnit.CentiliterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CentiliterPerMinute"/> + /// </summary> + public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CentiliterPerSecond"/> + /// </summary> + public double CentilitersPerSecond => As(VolumeFlowUnit.CentiliterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicCentimeterPerMinute"/> + /// </summary> + public double CubicCentimetersPerMinute => As(VolumeFlowUnit.CubicCentimeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicDecimeterPerMinute"/> + /// </summary> + public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicFootPerHour"/> + /// </summary> + public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicFootPerMinute"/> + /// </summary> + public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicFootPerSecond"/> + /// </summary> + public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicMeterPerDay"/> + /// </summary> + public double CubicMetersPerDay => As(VolumeFlowUnit.CubicMeterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicMeterPerHour"/> + /// </summary> + public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicMeterPerMinute"/> + /// </summary> + public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicMeterPerSecond"/> + /// </summary> + public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicMillimeterPerSecond"/> + /// </summary> + public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicYardPerDay"/> + /// </summary> + public double CubicYardsPerDay => As(VolumeFlowUnit.CubicYardPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicYardPerHour"/> + /// </summary> + public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicYardPerMinute"/> + /// </summary> + public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.CubicYardPerSecond"/> + /// </summary> + public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.DeciliterPerDay"/> + /// </summary> + public double DecilitersPerDay => As(VolumeFlowUnit.DeciliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.DeciliterPerHour"/> + /// </summary> + public double DecilitersPerHour => As(VolumeFlowUnit.DeciliterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.DeciliterPerMinute"/> + /// </summary> + public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.DeciliterPerSecond"/> + /// </summary> + public double DecilitersPerSecond => As(VolumeFlowUnit.DeciliterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.KiloliterPerDay"/> + /// </summary> + public double KilolitersPerDay => As(VolumeFlowUnit.KiloliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.KiloliterPerHour"/> + /// </summary> + public double KilolitersPerHour => As(VolumeFlowUnit.KiloliterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.KiloliterPerMinute"/> + /// </summary> + public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.KiloliterPerSecond"/> + /// </summary> + public double KilolitersPerSecond => As(VolumeFlowUnit.KiloliterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.KilousGallonPerMinute"/> + /// </summary> + public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.LiterPerDay"/> + /// </summary> + public double LitersPerDay => As(VolumeFlowUnit.LiterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.LiterPerHour"/> + /// </summary> + public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.LiterPerMinute"/> + /// </summary> + public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.LiterPerSecond"/> + /// </summary> + public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MegaliterPerDay"/> + /// </summary> + public double MegalitersPerDay => As(VolumeFlowUnit.MegaliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MegaukGallonPerSecond"/> + /// </summary> + public double MegaukGallonsPerSecond => As(VolumeFlowUnit.MegaukGallonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MicroliterPerDay"/> + /// </summary> + public double MicrolitersPerDay => As(VolumeFlowUnit.MicroliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MicroliterPerHour"/> + /// </summary> + public double MicrolitersPerHour => As(VolumeFlowUnit.MicroliterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MicroliterPerMinute"/> + /// </summary> + public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MicroliterPerSecond"/> + /// </summary> + public double MicrolitersPerSecond => As(VolumeFlowUnit.MicroliterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MilliliterPerDay"/> + /// </summary> + public double MillilitersPerDay => As(VolumeFlowUnit.MilliliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MilliliterPerHour"/> + /// </summary> + public double MillilitersPerHour => As(VolumeFlowUnit.MilliliterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MilliliterPerMinute"/> + /// </summary> + public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MilliliterPerSecond"/> + /// </summary> + public double MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.MillionUsGallonPerDay"/> + /// </summary> + public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.NanoliterPerDay"/> + /// </summary> + public double NanolitersPerDay => As(VolumeFlowUnit.NanoliterPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.NanoliterPerHour"/> + /// </summary> + public double NanolitersPerHour => As(VolumeFlowUnit.NanoliterPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.NanoliterPerMinute"/> + /// </summary> + public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.NanoliterPerSecond"/> + /// </summary> + public double NanolitersPerSecond => As(VolumeFlowUnit.NanoliterPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.OilBarrelPerDay"/> + /// </summary> + public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.OilBarrelPerHour"/> + /// </summary> + public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.OilBarrelPerMinute"/> + /// </summary> + public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.OilBarrelPerSecond"/> + /// </summary> + public double OilBarrelsPerSecond => As(VolumeFlowUnit.OilBarrelPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UkGallonPerDay"/> + /// </summary> + public double UkGallonsPerDay => As(VolumeFlowUnit.UkGallonPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UkGallonPerHour"/> + /// </summary> + public double UkGallonsPerHour => As(VolumeFlowUnit.UkGallonPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UkGallonPerMinute"/> + /// </summary> + public double UkGallonsPerMinute => As(VolumeFlowUnit.UkGallonPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UkGallonPerSecond"/> + /// </summary> + public double UkGallonsPerSecond => As(VolumeFlowUnit.UkGallonPerSecond); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UsGallonPerDay"/> + /// </summary> + public double UsGallonsPerDay => As(VolumeFlowUnit.UsGallonPerDay); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UsGallonPerHour"/> + /// </summary> + public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UsGallonPerMinute"/> + /// </summary> + public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowUnit.UsGallonPerSecond"/> + /// </summary> + public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VolumeFlowUnit -> BaseUnit + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.AcreFootPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.AcreFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.AcreFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.AcreFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CentiliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CentiliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CentiliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CentiliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicCentimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicDecimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMillimeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicYardPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicYardPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicYardPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicYardPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.DeciliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.DeciliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.DeciliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.DeciliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.KiloliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.KiloliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.KiloliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.KiloliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.KilousGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.LiterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.LiterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.LiterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.LiterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MegaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MegaukGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MicroliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MicroliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MicroliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MicroliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MilliliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.MillionUsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.NanoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.OilBarrelPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.OilBarrelPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.OilBarrelPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.OilBarrelPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UkGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UkGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UkGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UkGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UsGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UsGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.UsGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity); + + // Register in unit converter: BaseUnit -> VolumeFlowUnit + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicCentimeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicCentimeterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicDecimeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicDecimeterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMillimeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMillimeterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KilousGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.KilousGallonPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MegaliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MegaukGallonPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MillionUsGallonPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerSecond)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerDay)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerHour)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerMinute)); + unitConverter.SetConversionFunction<VolumeFlow>(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerSecond)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.AcreFootPerDay, new CultureInfo("en-US"), false, true, new string[]{"af/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.AcreFootPerHour, new CultureInfo("en-US"), false, true, new string[]{"af/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.AcreFootPerMinute, new CultureInfo("en-US"), false, true, new string[]{"af/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.AcreFootPerSecond, new CultureInfo("en-US"), false, true, new string[]{"af/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"cl/day", "cL/d", "cLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerHour, new CultureInfo("en-US"), false, true, new string[]{"cL/h", "cLPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"сл/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"cL/min", "cLPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"сл/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"cL/s", "cLPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CentiliterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"сл/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicCentimeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"cm³/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicCentimeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"см³/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicDecimeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"dm³/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicDecimeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"дм³/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicFootPerHour, new CultureInfo("en-US"), false, true, new string[]{"ft³/h", "cf/hr"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicFootPerMinute, new CultureInfo("en-US"), false, true, new string[]{"ft³/min", "CFM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicFootPerSecond, new CultureInfo("en-US"), false, true, new string[]{"ft³/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerDay, new CultureInfo("en-US"), false, true, new string[]{"m³/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerHour, new CultureInfo("en-US"), false, true, new string[]{"m³/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"м³/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"m³/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"м³/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"m³/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"м³/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMillimeterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mm³/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicMillimeterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мм³/с"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicYardPerDay, new CultureInfo("en-US"), false, true, new string[]{"cy/day"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicYardPerHour, new CultureInfo("en-US"), false, true, new string[]{"yd³/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicYardPerMinute, new CultureInfo("en-US"), false, true, new string[]{"yd³/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.CubicYardPerSecond, new CultureInfo("en-US"), false, true, new string[]{"yd³/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"dl/day", "dL/d", "dLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerHour, new CultureInfo("en-US"), false, true, new string[]{"dL/h", "dLPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"дл/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"dL/min", "dLPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"дл/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"dL/s", "dLPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.DeciliterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"дл/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"kl/day", "kL/d", "kLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerHour, new CultureInfo("en-US"), false, true, new string[]{"kL/h", "kLPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"кл/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kL/min", "kLPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"кл/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"kL/s", "kLPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KiloliterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"кл/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.KilousGallonPerMinute, new CultureInfo("en-US"), false, true, new string[]{"kgal (U.S.)/min", "KGPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerDay, new CultureInfo("en-US"), false, true, new string[]{"l/day", "L/d", "LPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerHour, new CultureInfo("en-US"), false, true, new string[]{"L/h", "LPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"л/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"L/min", "LPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"л/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"L/s", "LPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.LiterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"л/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MegaliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"Ml/day", "ML/d", "MLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MegaukGallonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"Mgal (imp.)/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"µl/day", "µL/d", "µLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerHour, new CultureInfo("en-US"), false, true, new string[]{"µL/h", "µLPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"мкл/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"µL/min", "µLPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"мкл/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"µL/s", "µLPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MicroliterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мкл/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"ml/day", "mL/d", "mLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerHour, new CultureInfo("en-US"), false, true, new string[]{"mL/h", "mLPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"мл/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"mL/min", "mLPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"мл/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"mL/s", "mLPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MilliliterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"мл/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.MillionUsGallonPerDay, new CultureInfo("en-US"), false, true, new string[]{"MGD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerDay, new CultureInfo("en-US"), false, true, new string[]{"nl/day", "nL/d", "nLPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerHour, new CultureInfo("en-US"), false, true, new string[]{"nL/h", "nLPH"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerHour, new CultureInfo("ru-RU"), false, true, new string[]{"нл/ч"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerMinute, new CultureInfo("en-US"), false, true, new string[]{"nL/min", "nLPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerMinute, new CultureInfo("ru-RU"), false, true, new string[]{"нл/мин"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerSecond, new CultureInfo("en-US"), false, true, new string[]{"nL/s", "nLPS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.NanoliterPerSecond, new CultureInfo("ru-RU"), false, true, new string[]{"нл/c"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.OilBarrelPerDay, new CultureInfo("en-US"), false, true, new string[]{"bbl/d", "BOPD"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.OilBarrelPerHour, new CultureInfo("en-US"), false, true, new string[]{"bbl/hr", "bph"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.OilBarrelPerMinute, new CultureInfo("en-US"), false, true, new string[]{"bbl/min", "bpm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.OilBarrelPerSecond, new CultureInfo("en-US"), false, true, new string[]{"bbl/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UkGallonPerDay, new CultureInfo("en-US"), false, true, new string[]{"gal (U. K.)/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UkGallonPerHour, new CultureInfo("en-US"), false, true, new string[]{"gal (imp.)/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UkGallonPerMinute, new CultureInfo("en-US"), false, true, new string[]{"gal (imp.)/min"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UkGallonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"gal (imp.)/s"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UsGallonPerDay, new CultureInfo("en-US"), false, true, new string[]{"gpd", "gal/d"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UsGallonPerHour, new CultureInfo("en-US"), false, true, new string[]{"gal (U.S.)/h"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UsGallonPerMinute, new CultureInfo("en-US"), false, true, new string[]{"gal (U.S.)/min", "GPM"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowUnit.UsGallonPerSecond, new CultureInfo("en-US"), false, true, new string[]{"gal (U.S.)/s"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VolumeFlowUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VolumeFlowUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.AcreFootPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromAcreFeetPerDay(QuantityValue acrefeetperday) + { + double value = (double) acrefeetperday; + return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.AcreFootPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromAcreFeetPerHour(QuantityValue acrefeetperhour) + { + double value = (double) acrefeetperhour; + return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.AcreFootPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromAcreFeetPerMinute(QuantityValue acrefeetperminute) + { + double value = (double) acrefeetperminute; + return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.AcreFootPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromAcreFeetPerSecond(QuantityValue acrefeetpersecond) + { + double value = (double) acrefeetpersecond; + return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CentiliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCentilitersPerDay(QuantityValue centilitersperday) + { + double value = (double) centilitersperday; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CentiliterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCentilitersPerHour(QuantityValue centilitersperhour) + { + double value = (double) centilitersperhour; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CentiliterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) + { + double value = (double) centilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CentiliterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCentilitersPerSecond(QuantityValue centiliterspersecond) + { + double value = (double) centiliterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicCentimeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicCentimetersPerMinute(QuantityValue cubiccentimetersperminute) + { + double value = (double) cubiccentimetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicCentimeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicDecimeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) + { + double value = (double) cubicdecimetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicFootPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) + { + double value = (double) cubicfeetperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicFootPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) + { + double value = (double) cubicfeetperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicFootPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) + { + double value = (double) cubicfeetpersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicMeterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicMetersPerDay(QuantityValue cubicmetersperday) + { + double value = (double) cubicmetersperday; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicMeterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) + { + double value = (double) cubicmetersperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicMeterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) + { + double value = (double) cubicmetersperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicMeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) + { + double value = (double) cubicmeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicMillimeterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicMillimetersPerSecond(QuantityValue cubicmillimeterspersecond) + { + double value = (double) cubicmillimeterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicMillimeterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicYardPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicYardsPerDay(QuantityValue cubicyardsperday) + { + double value = (double) cubicyardsperday; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicYardPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) + { + double value = (double) cubicyardsperhour; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicYardPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) + { + double value = (double) cubicyardsperminute; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.CubicYardPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) + { + double value = (double) cubicyardspersecond; + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.DeciliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromDecilitersPerDay(QuantityValue decilitersperday) + { + double value = (double) decilitersperday; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.DeciliterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromDecilitersPerHour(QuantityValue decilitersperhour) + { + double value = (double) decilitersperhour; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.DeciliterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) + { + double value = (double) decilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.DeciliterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromDecilitersPerSecond(QuantityValue deciliterspersecond) + { + double value = (double) deciliterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.KiloliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromKilolitersPerDay(QuantityValue kilolitersperday) + { + double value = (double) kilolitersperday; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.KiloliterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromKilolitersPerHour(QuantityValue kilolitersperhour) + { + double value = (double) kilolitersperhour; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.KiloliterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) + { + double value = (double) kilolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.KiloliterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromKilolitersPerSecond(QuantityValue kiloliterspersecond) + { + double value = (double) kiloliterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.KilousGallonPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromKilousGallonsPerMinute(QuantityValue kilousgallonsperminute) + { + double value = (double) kilousgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.KilousGallonPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.LiterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromLitersPerDay(QuantityValue litersperday) + { + double value = (double) litersperday; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.LiterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) + { + double value = (double) litersperhour; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.LiterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) + { + double value = (double) litersperminute; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.LiterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) + { + double value = (double) literspersecond; + return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MegaliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMegalitersPerDay(QuantityValue megalitersperday) + { + double value = (double) megalitersperday; + return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MegaukGallonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMegaukGallonsPerSecond(QuantityValue megaukgallonspersecond) + { + double value = (double) megaukgallonspersecond; + return new VolumeFlow(value, VolumeFlowUnit.MegaukGallonPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MicroliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMicrolitersPerDay(QuantityValue microlitersperday) + { + double value = (double) microlitersperday; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MicroliterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMicrolitersPerHour(QuantityValue microlitersperhour) + { + double value = (double) microlitersperhour; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MicroliterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) + { + double value = (double) microlitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MicroliterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMicrolitersPerSecond(QuantityValue microliterspersecond) + { + double value = (double) microliterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MilliliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMillilitersPerDay(QuantityValue millilitersperday) + { + double value = (double) millilitersperday; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MilliliterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMillilitersPerHour(QuantityValue millilitersperhour) + { + double value = (double) millilitersperhour; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MilliliterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) + { + double value = (double) millilitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MilliliterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMillilitersPerSecond(QuantityValue milliliterspersecond) + { + double value = (double) milliliterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.MillionUsGallonPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) + { + double value = (double) millionusgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.NanoliterPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromNanolitersPerDay(QuantityValue nanolitersperday) + { + double value = (double) nanolitersperday; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.NanoliterPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromNanolitersPerHour(QuantityValue nanolitersperhour) + { + double value = (double) nanolitersperhour; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.NanoliterPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) + { + double value = (double) nanolitersperminute; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.NanoliterPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromNanolitersPerSecond(QuantityValue nanoliterspersecond) + { + double value = (double) nanoliterspersecond; + return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.OilBarrelPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) + { + double value = (double) oilbarrelsperday; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.OilBarrelPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromOilBarrelsPerHour(QuantityValue oilbarrelsperhour) + { + double value = (double) oilbarrelsperhour; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.OilBarrelPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue oilbarrelsperminute) + { + double value = (double) oilbarrelsperminute; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.OilBarrelPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromOilBarrelsPerSecond(QuantityValue oilbarrelspersecond) + { + double value = (double) oilbarrelspersecond; + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UkGallonPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUkGallonsPerDay(QuantityValue ukgallonsperday) + { + double value = (double) ukgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UkGallonPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUkGallonsPerHour(QuantityValue ukgallonsperhour) + { + double value = (double) ukgallonsperhour; + return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UkGallonPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUkGallonsPerMinute(QuantityValue ukgallonsperminute) + { + double value = (double) ukgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UkGallonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUkGallonsPerSecond(QuantityValue ukgallonspersecond) + { + double value = (double) ukgallonspersecond; + return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerSecond); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UsGallonPerDay"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUsGallonsPerDay(QuantityValue usgallonsperday) + { + double value = (double) usgallonsperday; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerDay); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UsGallonPerHour"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) + { + double value = (double) usgallonsperhour; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UsGallonPerMinute"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) + { + double value = (double) usgallonsperminute; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); + } + + /// <summary> + /// Creates a <see cref="VolumeFlow"/> from <see cref="VolumeFlowUnit.UsGallonPerSecond"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) + { + double value = (double) usgallonspersecond; + return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VolumeFlowUnit" /> to <see cref="VolumeFlow" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>VolumeFlow unit value.</returns> + public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) + { + return new VolumeFlow((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static VolumeFlow Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static VolumeFlow Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<VolumeFlow, VolumeFlowUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out VolumeFlow result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out VolumeFlow result) + { + return QuantityParser.Default.TryParse<VolumeFlow, VolumeFlowUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeFlowUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeFlowUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VolumeFlowUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VolumeFlowUnit)"/> + public static bool TryParseUnit(string str, out VolumeFlowUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeFlowUnit unit) + { + return UnitParser.Default.TryParse<VolumeFlowUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static VolumeFlow operator -(VolumeFlow right) + { + return new VolumeFlow(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumeFlow"/> from adding two <see cref="VolumeFlow"/>.</summary> + public static VolumeFlow operator +(VolumeFlow left, VolumeFlow right) + { + return new VolumeFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumeFlow"/> from subtracting two <see cref="VolumeFlow"/>.</summary> + public static VolumeFlow operator -(VolumeFlow left, VolumeFlow right) + { + return new VolumeFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumeFlow"/> from multiplying value and <see cref="VolumeFlow"/>.</summary> + public static VolumeFlow operator *(double left, VolumeFlow right) + { + return new VolumeFlow(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumeFlow"/> from multiplying value and <see cref="VolumeFlow"/>.</summary> + public static VolumeFlow operator *(VolumeFlow left, double right) + { + return new VolumeFlow(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="VolumeFlow"/> from dividing <see cref="VolumeFlow"/> by value.</summary> + public static VolumeFlow operator /(VolumeFlow left, double right) + { + return new VolumeFlow(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="VolumeFlow"/> by <see cref="VolumeFlow"/>.</summary> + public static double operator /(VolumeFlow left, VolumeFlow right) + { + return left.CubicMetersPerSecond / right.CubicMetersPerSecond; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(VolumeFlow left, VolumeFlow right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(VolumeFlow left, VolumeFlow right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(VolumeFlow left, VolumeFlow right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(VolumeFlow left, VolumeFlow right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="VolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(VolumeFlow left, VolumeFlow right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="VolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(VolumeFlow left, VolumeFlow right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is VolumeFlow otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumeFlow"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlow, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(VolumeFlow other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="VolumeFlow"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is VolumeFlow otherQuantity)) throw new ArgumentException("Expected type VolumeFlow.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="VolumeFlow"/> with another <see cref="VolumeFlow"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(VolumeFlow other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another VolumeFlow within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + 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 = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current VolumeFlow.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VolumeFlowUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VolumeFlowUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this VolumeFlow to another VolumeFlow with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A VolumeFlow with the specified unit.</returns> + public VolumeFlow ToUnit(VolumeFlowUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="VolumeFlow"/> to another <see cref="VolumeFlow"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A VolumeFlow with the specified unit.</returns> + public VolumeFlow ToUnit(VolumeFlowUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(VolumeFlow), Unit, typeof(VolumeFlow), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (VolumeFlow)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="VolumeFlow"/> to another <see cref="VolumeFlow"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="VolumeFlow"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VolumeFlowUnit unit, [NotNullWhen(true)] out VolumeFlow? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + VolumeFlow? convertedOrNull = (Unit, unit) switch + { + // VolumeFlowUnit -> BaseUnit + (VolumeFlowUnit.AcreFootPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 70.0457, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.AcreFootPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 2.91857, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.AcreFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 0.0486427916, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.AcreFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 0.000810713194, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CentiliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CentiliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 3600000.000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CentiliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 60000.00000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CentiliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicCentimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1.6666666666667e-8, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicDecimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 60000.00000, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicFootPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 7.8657907199999087346816086183876e-6, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 2118.88000326, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 35.314666721, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicMeterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 86400, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicMeterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 3600, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicMeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 60, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicMillimeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1e-9, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicYardPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 113007, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicYardPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 2.1237634944E-4, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicYardPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.0127425809664, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.CubicYardPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.764554857984, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.DeciliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.DeciliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 3600000.000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.DeciliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 60000.00000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.DeciliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.KiloliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.KiloliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 3600000.000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.KiloliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 60000.00000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.KiloliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.KilousGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 15.850323141489, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.LiterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 86400000, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.LiterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 3600000.000, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.LiterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 60000.00000, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.LiterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 1000, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MegaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MegaukGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 219.969) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MicroliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MicroliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 3600000.000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MicroliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 60000.00000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MicroliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MilliliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 3600000.000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 60000.00000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.MillionUsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 22.824465227, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 86400000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 3600000.000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 60000.00000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.NanoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.OilBarrelPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1.8401307283333333333333333333333e-6, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.OilBarrelPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 4.41631375e-5, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.OilBarrelPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 2.64978825e-3, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.OilBarrelPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 6.28981, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UkGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 19005304, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UkGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 791887.667, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UkGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 13198.2, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UkGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 219.969, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 22824465.227, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UsGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 951019.38848933424, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UsGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 15850.323141489, VolumeFlowUnit.CubicMeterPerSecond), + (VolumeFlowUnit.UsGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 264.1720523581484, VolumeFlowUnit.CubicMeterPerSecond), + + // BaseUnit -> VolumeFlowUnit + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerDay) => new VolumeFlow(_value * 70.0457, VolumeFlowUnit.AcreFootPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerHour) => new VolumeFlow(_value * 2.91857, VolumeFlowUnit.AcreFootPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerMinute) => new VolumeFlow(_value * 0.0486427916, VolumeFlowUnit.AcreFootPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerSecond) => new VolumeFlow(_value * 0.000810713194, VolumeFlowUnit.AcreFootPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerDay) => new VolumeFlow((_value * 86400000) / 1e-2d, VolumeFlowUnit.CentiliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerHour) => new VolumeFlow((_value * 3600000.000) / 1e-2d, VolumeFlowUnit.CentiliterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerMinute) => new VolumeFlow((_value * 60000.00000) / 1e-2d, VolumeFlowUnit.CentiliterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-2d, VolumeFlowUnit.CentiliterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicCentimeterPerMinute) => new VolumeFlow(_value / 1.6666666666667e-8, VolumeFlowUnit.CubicCentimeterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicDecimeterPerMinute) => new VolumeFlow(_value * 60000.00000, VolumeFlowUnit.CubicDecimeterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerHour) => new VolumeFlow(_value / 7.8657907199999087346816086183876e-6, VolumeFlowUnit.CubicFootPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerMinute) => new VolumeFlow(_value * 2118.88000326, VolumeFlowUnit.CubicFootPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerSecond) => new VolumeFlow(_value * 35.314666721, VolumeFlowUnit.CubicFootPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerDay) => new VolumeFlow(_value * 86400, VolumeFlowUnit.CubicMeterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerHour) => new VolumeFlow(_value * 3600, VolumeFlowUnit.CubicMeterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerMinute) => new VolumeFlow(_value * 60, VolumeFlowUnit.CubicMeterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMillimeterPerSecond) => new VolumeFlow(_value / 1e-9, VolumeFlowUnit.CubicMillimeterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerDay) => new VolumeFlow(_value * 113007, VolumeFlowUnit.CubicYardPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerHour) => new VolumeFlow(_value / 2.1237634944E-4, VolumeFlowUnit.CubicYardPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerMinute) => new VolumeFlow(_value / 0.0127425809664, VolumeFlowUnit.CubicYardPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerSecond) => new VolumeFlow(_value / 0.764554857984, VolumeFlowUnit.CubicYardPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerDay) => new VolumeFlow((_value * 86400000) / 1e-1d, VolumeFlowUnit.DeciliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerHour) => new VolumeFlow((_value * 3600000.000) / 1e-1d, VolumeFlowUnit.DeciliterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerMinute) => new VolumeFlow((_value * 60000.00000) / 1e-1d, VolumeFlowUnit.DeciliterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-1d, VolumeFlowUnit.DeciliterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerDay) => new VolumeFlow((_value * 86400000) / 1e3d, VolumeFlowUnit.KiloliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerHour) => new VolumeFlow((_value * 3600000.000) / 1e3d, VolumeFlowUnit.KiloliterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerMinute) => new VolumeFlow((_value * 60000.00000) / 1e3d, VolumeFlowUnit.KiloliterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerSecond) => new VolumeFlow((_value * 1000) / 1e3d, VolumeFlowUnit.KiloliterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KilousGallonPerMinute) => new VolumeFlow(_value * 15.850323141489, VolumeFlowUnit.KilousGallonPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerDay) => new VolumeFlow(_value * 86400000, VolumeFlowUnit.LiterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerHour) => new VolumeFlow(_value * 3600000.000, VolumeFlowUnit.LiterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerMinute) => new VolumeFlow(_value * 60000.00000, VolumeFlowUnit.LiterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerSecond) => new VolumeFlow(_value * 1000, VolumeFlowUnit.LiterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerDay) => new VolumeFlow((_value * 86400000) / 1e6d, VolumeFlowUnit.MegaliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerSecond) => new VolumeFlow((_value * 219.969) / 1e6d, VolumeFlowUnit.MegaukGallonPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerDay) => new VolumeFlow((_value * 86400000) / 1e-6d, VolumeFlowUnit.MicroliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerHour) => new VolumeFlow((_value * 3600000.000) / 1e-6d, VolumeFlowUnit.MicroliterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerMinute) => new VolumeFlow((_value * 60000.00000) / 1e-6d, VolumeFlowUnit.MicroliterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-6d, VolumeFlowUnit.MicroliterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerDay) => new VolumeFlow((_value * 86400000) / 1e-3d, VolumeFlowUnit.MilliliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour) => new VolumeFlow((_value * 3600000.000) / 1e-3d, VolumeFlowUnit.MilliliterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute) => new VolumeFlow((_value * 60000.00000) / 1e-3d, VolumeFlowUnit.MilliliterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-3d, VolumeFlowUnit.MilliliterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonPerDay) => new VolumeFlow(_value * 22.824465227, VolumeFlowUnit.MillionUsGallonPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay) => new VolumeFlow((_value * 86400000) / 1e-9d, VolumeFlowUnit.NanoliterPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour) => new VolumeFlow((_value * 3600000.000) / 1e-9d, VolumeFlowUnit.NanoliterPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute) => new VolumeFlow((_value * 60000.00000) / 1e-9d, VolumeFlowUnit.NanoliterPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-9d, VolumeFlowUnit.NanoliterPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerDay) => new VolumeFlow(_value / 1.8401307283333333333333333333333e-6, VolumeFlowUnit.OilBarrelPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerHour) => new VolumeFlow(_value / 4.41631375e-5, VolumeFlowUnit.OilBarrelPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerMinute) => new VolumeFlow(_value / 2.64978825e-3, VolumeFlowUnit.OilBarrelPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerSecond) => new VolumeFlow(_value * 6.28981, VolumeFlowUnit.OilBarrelPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerDay) => new VolumeFlow(_value * 19005304, VolumeFlowUnit.UkGallonPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerHour) => new VolumeFlow(_value * 791887.667, VolumeFlowUnit.UkGallonPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerMinute) => new VolumeFlow(_value * 13198.2, VolumeFlowUnit.UkGallonPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerSecond) => new VolumeFlow(_value * 219.969, VolumeFlowUnit.UkGallonPerSecond), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerDay) => new VolumeFlow(_value * 22824465.227, VolumeFlowUnit.UsGallonPerDay), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerHour) => new VolumeFlow(_value * 951019.38848933424, VolumeFlowUnit.UsGallonPerHour), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerMinute) => new VolumeFlow(_value * 15850.323141489, VolumeFlowUnit.UsGallonPerMinute), + (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerSecond) => new VolumeFlow(_value * 264.1720523581484, VolumeFlowUnit.UsGallonPerSecond), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VolumeFlowUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VolumeFlowUnit> IQuantity<VolumeFlowUnit>.ToUnit(VolumeFlowUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VolumeFlowUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(VolumeFlow)) + return this; + else if (conversionType == typeof(VolumeFlowUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return VolumeFlow.Info; + else if (conversionType == typeof(BaseDimensions)) + return VolumeFlow.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlowUnit.g.cs b/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlowUnit.g.cs new file mode 100644 index 0000000000..08291ef5da --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeFlow/VolumeFlowUnit.g.cs @@ -0,0 +1,93 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VolumeFlowUnit + { + AcreFootPerDay = 1, + AcreFootPerHour = 2, + AcreFootPerMinute = 3, + AcreFootPerSecond = 4, + CentiliterPerDay = 5, + CentiliterPerHour = 6, + CentiliterPerMinute = 7, + CentiliterPerSecond = 8, + CubicCentimeterPerMinute = 9, + CubicDecimeterPerMinute = 10, + CubicFootPerHour = 11, + CubicFootPerMinute = 12, + CubicFootPerSecond = 13, + CubicMeterPerDay = 14, + CubicMeterPerHour = 15, + CubicMeterPerMinute = 16, + CubicMeterPerSecond = 17, + CubicMillimeterPerSecond = 18, + CubicYardPerDay = 19, + CubicYardPerHour = 20, + CubicYardPerMinute = 21, + CubicYardPerSecond = 22, + DeciliterPerDay = 23, + DeciliterPerHour = 24, + DeciliterPerMinute = 25, + DeciliterPerSecond = 26, + KiloliterPerDay = 27, + KiloliterPerHour = 28, + KiloliterPerMinute = 29, + KiloliterPerSecond = 30, + KilousGallonPerMinute = 31, + LiterPerDay = 32, + LiterPerHour = 33, + LiterPerMinute = 34, + LiterPerSecond = 35, + MegaliterPerDay = 36, + MegaukGallonPerSecond = 37, + MicroliterPerDay = 38, + MicroliterPerHour = 39, + MicroliterPerMinute = 40, + MicroliterPerSecond = 41, + MilliliterPerDay = 42, + MilliliterPerHour = 43, + MilliliterPerMinute = 44, + MilliliterPerSecond = 45, + MillionUsGallonPerDay = 66, + NanoliterPerDay = 47, + NanoliterPerHour = 48, + NanoliterPerMinute = 49, + NanoliterPerSecond = 50, + OilBarrelPerDay = 51, + OilBarrelPerHour = 52, + OilBarrelPerMinute = 53, + OilBarrelPerSecond = 54, + UkGallonPerDay = 55, + UkGallonPerHour = 56, + UkGallonPerMinute = 57, + UkGallonPerSecond = 58, + UsGallonPerDay = 59, + UsGallonPerHour = 60, + UsGallonPerMinute = 61, + UsGallonPerSecond = 62, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerArea.csproj b/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerArea.csproj new file mode 100644 index 0000000000..786868eef4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerArea.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET VolumeFlowPerArea</Title> + <Description>Adds VolumeFlowPerArea units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>volumeflowperarea unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{753bcc52-c451-8b29-6ae7-520b02ee6960}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.VolumeFlowPerArea</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerArea.g.cs b/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerArea.g.cs new file mode 100644 index 0000000000..9d77f3c96f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerArea.g.cs @@ -0,0 +1,859 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// + /// </summary> + [DataContract] + public readonly partial struct VolumeFlowPerArea : IArithmeticQuantity<VolumeFlowPerArea, VolumeFlowPerAreaUnit, double>, IEquatable<VolumeFlowPerArea>, IComparable, IComparable<VolumeFlowPerArea>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VolumeFlowPerAreaUnit? _unit; + + static VolumeFlowPerArea() + { + BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); + BaseUnit = VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter; + Units = Enum.GetValues(typeof(VolumeFlowPerAreaUnit)).Cast<VolumeFlowPerAreaUnit>().ToArray(); + Zero = new VolumeFlowPerArea(0, BaseUnit); + Info = new QuantityInfo<VolumeFlowPerAreaUnit>("VolumeFlowPerArea", + new UnitInfo<VolumeFlowPerAreaUnit>[] + { + new UnitInfo<VolumeFlowPerAreaUnit>(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, "CubicFeetPerMinutePerSquareFoot", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)), + new UnitInfo<VolumeFlowPerAreaUnit>(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "CubicMetersPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public VolumeFlowPerArea(double value, VolumeFlowPerAreaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="VolumeFlowPerArea" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VolumeFlowPerAreaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of VolumeFlowPerArea, which is CubicMeterPerSecondPerSquareMeter. All conversions go via this value. + /// </summary> + public static VolumeFlowPerAreaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the VolumeFlowPerArea quantity. + /// </summary> + public static VolumeFlowPerAreaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecondPerSquareMeter. + /// </summary> + public static VolumeFlowPerArea Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static VolumeFlowPerArea AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VolumeFlowPerAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VolumeFlowPerAreaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => VolumeFlowPerArea.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot"/> + /// </summary> + public double CubicFeetPerMinutePerSquareFoot => As(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter"/> + /// </summary> + public double CubicMetersPerSecondPerSquareMeter => As(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VolumeFlowPerAreaUnit -> BaseUnit + unitConverter.SetConversionFunction<VolumeFlowPerArea>(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => quantity.ToUnit(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<VolumeFlowPerArea>(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> VolumeFlowPerAreaUnit + unitConverter.SetConversionFunction<VolumeFlowPerArea>(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, quantity => quantity.ToUnit(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, new CultureInfo("en-US"), false, true, new string[]{"CFM/ft²"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, new CultureInfo("en-US"), false, true, new string[]{"m³/(s·m²)"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VolumeFlowPerAreaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VolumeFlowPerAreaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="VolumeFlowPerArea"/> from <see cref="VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(QuantityValue cubicfeetperminutepersquarefoot) + { + double value = (double) cubicfeetperminutepersquarefoot; + return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); + } + + /// <summary> + /// Creates a <see cref="VolumeFlowPerArea"/> from <see cref="VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(QuantityValue cubicmeterspersecondpersquaremeter) + { + double value = (double) cubicmeterspersecondpersquaremeter; + return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VolumeFlowPerAreaUnit" /> to <see cref="VolumeFlowPerArea" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>VolumeFlowPerArea unit value.</returns> + public static VolumeFlowPerArea From(QuantityValue value, VolumeFlowPerAreaUnit fromUnit) + { + return new VolumeFlowPerArea((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static VolumeFlowPerArea Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static VolumeFlowPerArea Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<VolumeFlowPerArea, VolumeFlowPerAreaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out VolumeFlowPerArea result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out VolumeFlowPerArea result) + { + return QuantityParser.Default.TryParse<VolumeFlowPerArea, VolumeFlowPerAreaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeFlowPerAreaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumeFlowPerAreaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VolumeFlowPerAreaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VolumeFlowPerAreaUnit)"/> + public static bool TryParseUnit(string str, out VolumeFlowPerAreaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumeFlowPerAreaUnit unit) + { + return UnitParser.Default.TryParse<VolumeFlowPerAreaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static VolumeFlowPerArea operator -(VolumeFlowPerArea right) + { + return new VolumeFlowPerArea(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumeFlowPerArea"/> from adding two <see cref="VolumeFlowPerArea"/>.</summary> + public static VolumeFlowPerArea operator +(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return new VolumeFlowPerArea(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumeFlowPerArea"/> from subtracting two <see cref="VolumeFlowPerArea"/>.</summary> + public static VolumeFlowPerArea operator -(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return new VolumeFlowPerArea(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumeFlowPerArea"/> from multiplying value and <see cref="VolumeFlowPerArea"/>.</summary> + public static VolumeFlowPerArea operator *(double left, VolumeFlowPerArea right) + { + return new VolumeFlowPerArea(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumeFlowPerArea"/> from multiplying value and <see cref="VolumeFlowPerArea"/>.</summary> + public static VolumeFlowPerArea operator *(VolumeFlowPerArea left, double right) + { + return new VolumeFlowPerArea(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="VolumeFlowPerArea"/> from dividing <see cref="VolumeFlowPerArea"/> by value.</summary> + public static VolumeFlowPerArea operator /(VolumeFlowPerArea left, double right) + { + return new VolumeFlowPerArea(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="VolumeFlowPerArea"/> by <see cref="VolumeFlowPerArea"/>.</summary> + public static double operator /(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.CubicMetersPerSecondPerSquareMeter / right.CubicMetersPerSecondPerSquareMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="VolumeFlowPerArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlowPerArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="VolumeFlowPerArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlowPerArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(VolumeFlowPerArea left, VolumeFlowPerArea right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumeFlowPerArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlowPerArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is VolumeFlowPerArea otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumeFlowPerArea"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumeFlowPerArea, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(VolumeFlowPerArea other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="VolumeFlowPerArea"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is VolumeFlowPerArea otherQuantity)) throw new ArgumentException("Expected type VolumeFlowPerArea.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="VolumeFlowPerArea"/> with another <see cref="VolumeFlowPerArea"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(VolumeFlowPerArea other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another VolumeFlowPerArea within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(VolumeFlowPerArea other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current VolumeFlowPerArea.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VolumeFlowPerAreaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VolumeFlowPerAreaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this VolumeFlowPerArea to another VolumeFlowPerArea with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A VolumeFlowPerArea with the specified unit.</returns> + public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="VolumeFlowPerArea"/> to another <see cref="VolumeFlowPerArea"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A VolumeFlowPerArea with the specified unit.</returns> + public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(VolumeFlowPerArea), Unit, typeof(VolumeFlowPerArea), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (VolumeFlowPerArea)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="VolumeFlowPerArea"/> to another <see cref="VolumeFlowPerArea"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="VolumeFlowPerArea"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VolumeFlowPerAreaUnit unit, [NotNullWhen(true)] out VolumeFlowPerArea? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + VolumeFlowPerArea? convertedOrNull = (Unit, unit) switch + { + // VolumeFlowPerAreaUnit -> BaseUnit + (VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter) => new VolumeFlowPerArea(_value / 196.850394, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter), + + // BaseUnit -> VolumeFlowPerAreaUnit + (VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot) => new VolumeFlowPerArea(_value * 196.850394, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VolumeFlowPerAreaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VolumeFlowPerAreaUnit> IQuantity<VolumeFlowPerAreaUnit>.ToUnit(VolumeFlowPerAreaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VolumeFlowPerAreaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(VolumeFlowPerArea)) + return this; + else if (conversionType == typeof(VolumeFlowPerAreaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return VolumeFlowPerArea.Info; + else if (conversionType == typeof(BaseDimensions)) + return VolumeFlowPerArea.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerAreaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerAreaUnit.g.cs new file mode 100644 index 0000000000..abcdea8f8f --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumeFlowPerArea/VolumeFlowPerAreaUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VolumeFlowPerAreaUnit + { + CubicFootPerMinutePerSquareFoot = 1, + CubicMeterPerSecondPerSquareMeter = 2, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLength.csproj b/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLength.csproj new file mode 100644 index 0000000000..ec1288c625 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLength.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET VolumePerLength</Title> + <Description>Adds VolumePerLength units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>volumeperlength unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{b66e3a3e-7945-3d40-24ef-73fa6e1b8d41}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.VolumePerLength</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLength.g.cs b/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLength.g.cs new file mode 100644 index 0000000000..0f269848be --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLength.g.cs @@ -0,0 +1,964 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Volume, typically of fluid, that a container can hold within a unit of length. + /// </summary> + [DataContract] + public readonly partial struct VolumePerLength : IArithmeticQuantity<VolumePerLength, VolumePerLengthUnit, double>, IEquatable<VolumePerLength>, IComparable, IComparable<VolumePerLength>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VolumePerLengthUnit? _unit; + + static VolumePerLength() + { + BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + BaseUnit = VolumePerLengthUnit.CubicMeterPerMeter; + Units = Enum.GetValues(typeof(VolumePerLengthUnit)).Cast<VolumePerLengthUnit>().ToArray(); + Zero = new VolumePerLength(0, BaseUnit); + Info = new QuantityInfo<VolumePerLengthUnit>("VolumePerLength", + new UnitInfo<VolumePerLengthUnit>[] + { + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.CubicMeterPerMeter, "CubicMetersPerMeter", new BaseUnits(length: LengthUnit.Meter)), + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.CubicYardPerFoot, "CubicYardsPerFoot", BaseUnits.Undefined), + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, "CubicYardsPerUsSurveyFoot", BaseUnits.Undefined), + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.LiterPerKilometer, "LitersPerKilometer", BaseUnits.Undefined), + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.LiterPerMeter, "LitersPerMeter", new BaseUnits(length: LengthUnit.Decimeter)), + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.LiterPerMillimeter, "LitersPerMillimeter", BaseUnits.Undefined), + new UnitInfo<VolumePerLengthUnit>(VolumePerLengthUnit.OilBarrelPerFoot, "OilBarrelsPerFoot", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public VolumePerLength(double value, VolumePerLengthUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="VolumePerLength" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VolumePerLengthUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of VolumePerLength, which is CubicMeterPerMeter. All conversions go via this value. + /// </summary> + public static VolumePerLengthUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the VolumePerLength quantity. + /// </summary> + public static VolumePerLengthUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerMeter. + /// </summary> + public static VolumePerLength Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static VolumePerLength AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VolumePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VolumePerLengthUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => VolumePerLength.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.CubicMeterPerMeter"/> + /// </summary> + public double CubicMetersPerMeter => As(VolumePerLengthUnit.CubicMeterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.CubicYardPerFoot"/> + /// </summary> + public double CubicYardsPerFoot => As(VolumePerLengthUnit.CubicYardPerFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.CubicYardPerUsSurveyFoot"/> + /// </summary> + public double CubicYardsPerUsSurveyFoot => As(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.LiterPerKilometer"/> + /// </summary> + public double LitersPerKilometer => As(VolumePerLengthUnit.LiterPerKilometer); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.LiterPerMeter"/> + /// </summary> + public double LitersPerMeter => As(VolumePerLengthUnit.LiterPerMeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.LiterPerMillimeter"/> + /// </summary> + public double LitersPerMillimeter => As(VolumePerLengthUnit.LiterPerMillimeter); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumePerLengthUnit.OilBarrelPerFoot"/> + /// </summary> + public double OilBarrelsPerFoot => As(VolumePerLengthUnit.OilBarrelPerFoot); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VolumePerLengthUnit -> BaseUnit + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicYardPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.LiterPerKilometer, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.LiterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.LiterPerMillimeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.OilBarrelPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity); + + // Register in unit converter: BaseUnit -> VolumePerLengthUnit + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicYardPerFoot)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerUsSurveyFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicYardPerUsSurveyFoot)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerKilometer, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerKilometer)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerMeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMillimeter, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerMillimeter)); + unitConverter.SetConversionFunction<VolumePerLength>(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.OilBarrelPerFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.OilBarrelPerFoot)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.CubicMeterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"m³/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.CubicYardPerFoot, new CultureInfo("en-US"), false, true, new string[]{"yd³/ft"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, new CultureInfo("en-US"), false, true, new string[]{"yd³/ftUS"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.LiterPerKilometer, new CultureInfo("en-US"), false, true, new string[]{"l/km"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.LiterPerMeter, new CultureInfo("en-US"), false, true, new string[]{"l/m"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.LiterPerMillimeter, new CultureInfo("en-US"), false, true, new string[]{"l/mm"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumePerLengthUnit.OilBarrelPerFoot, new CultureInfo("en-US"), false, true, new string[]{"bbl/ft"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VolumePerLengthUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VolumePerLengthUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.CubicMeterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromCubicMetersPerMeter(QuantityValue cubicmeterspermeter) + { + double value = (double) cubicmeterspermeter; + return new VolumePerLength(value, VolumePerLengthUnit.CubicMeterPerMeter); + } + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.CubicYardPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromCubicYardsPerFoot(QuantityValue cubicyardsperfoot) + { + double value = (double) cubicyardsperfoot; + return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerFoot); + } + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.CubicYardPerUsSurveyFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromCubicYardsPerUsSurveyFoot(QuantityValue cubicyardsperussurveyfoot) + { + double value = (double) cubicyardsperussurveyfoot; + return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerUsSurveyFoot); + } + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.LiterPerKilometer"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromLitersPerKilometer(QuantityValue litersperkilometer) + { + double value = (double) litersperkilometer; + return new VolumePerLength(value, VolumePerLengthUnit.LiterPerKilometer); + } + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.LiterPerMeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromLitersPerMeter(QuantityValue literspermeter) + { + double value = (double) literspermeter; + return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMeter); + } + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.LiterPerMillimeter"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromLitersPerMillimeter(QuantityValue literspermillimeter) + { + double value = (double) literspermillimeter; + return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMillimeter); + } + + /// <summary> + /// Creates a <see cref="VolumePerLength"/> from <see cref="VolumePerLengthUnit.OilBarrelPerFoot"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumePerLength FromOilBarrelsPerFoot(QuantityValue oilbarrelsperfoot) + { + double value = (double) oilbarrelsperfoot; + return new VolumePerLength(value, VolumePerLengthUnit.OilBarrelPerFoot); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VolumePerLengthUnit" /> to <see cref="VolumePerLength" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>VolumePerLength unit value.</returns> + public static VolumePerLength From(QuantityValue value, VolumePerLengthUnit fromUnit) + { + return new VolumePerLength((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static VolumePerLength Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static VolumePerLength Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<VolumePerLength, VolumePerLengthUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out VolumePerLength result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out VolumePerLength result) + { + return QuantityParser.Default.TryParse<VolumePerLength, VolumePerLengthUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumePerLengthUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumePerLengthUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VolumePerLengthUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VolumePerLengthUnit)"/> + public static bool TryParseUnit(string str, out VolumePerLengthUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumePerLengthUnit unit) + { + return UnitParser.Default.TryParse<VolumePerLengthUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static VolumePerLength operator -(VolumePerLength right) + { + return new VolumePerLength(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumePerLength"/> from adding two <see cref="VolumePerLength"/>.</summary> + public static VolumePerLength operator +(VolumePerLength left, VolumePerLength right) + { + return new VolumePerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumePerLength"/> from subtracting two <see cref="VolumePerLength"/>.</summary> + public static VolumePerLength operator -(VolumePerLength left, VolumePerLength right) + { + return new VolumePerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumePerLength"/> from multiplying value and <see cref="VolumePerLength"/>.</summary> + public static VolumePerLength operator *(double left, VolumePerLength right) + { + return new VolumePerLength(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumePerLength"/> from multiplying value and <see cref="VolumePerLength"/>.</summary> + public static VolumePerLength operator *(VolumePerLength left, double right) + { + return new VolumePerLength(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="VolumePerLength"/> from dividing <see cref="VolumePerLength"/> by value.</summary> + public static VolumePerLength operator /(VolumePerLength left, double right) + { + return new VolumePerLength(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="VolumePerLength"/> by <see cref="VolumePerLength"/>.</summary> + public static double operator /(VolumePerLength left, VolumePerLength right) + { + return left.CubicMetersPerMeter / right.CubicMetersPerMeter; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(VolumePerLength left, VolumePerLength right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(VolumePerLength left, VolumePerLength right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(VolumePerLength left, VolumePerLength right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(VolumePerLength left, VolumePerLength right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="VolumePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(VolumePerLength left, VolumePerLength right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="VolumePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(VolumePerLength left, VolumePerLength right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is VolumePerLength otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumePerLength"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumePerLength, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(VolumePerLength other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="VolumePerLength"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is VolumePerLength otherQuantity)) throw new ArgumentException("Expected type VolumePerLength.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="VolumePerLength"/> with another <see cref="VolumePerLength"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(VolumePerLength other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another VolumePerLength within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(VolumePerLength other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current VolumePerLength.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VolumePerLengthUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VolumePerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this VolumePerLength to another VolumePerLength with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A VolumePerLength with the specified unit.</returns> + public VolumePerLength ToUnit(VolumePerLengthUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="VolumePerLength"/> to another <see cref="VolumePerLength"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A VolumePerLength with the specified unit.</returns> + public VolumePerLength ToUnit(VolumePerLengthUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(VolumePerLength), Unit, typeof(VolumePerLength), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (VolumePerLength)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="VolumePerLength"/> to another <see cref="VolumePerLength"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="VolumePerLength"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VolumePerLengthUnit unit, [NotNullWhen(true)] out VolumePerLength? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + VolumePerLength? convertedOrNull = (Unit, unit) switch + { + // VolumePerLengthUnit -> BaseUnit + (VolumePerLengthUnit.CubicYardPerFoot, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 2.50838208, VolumePerLengthUnit.CubicMeterPerMeter), + (VolumePerLengthUnit.CubicYardPerUsSurveyFoot, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 2.50837706323584, VolumePerLengthUnit.CubicMeterPerMeter), + (VolumePerLengthUnit.LiterPerKilometer, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value / 1e6, VolumePerLengthUnit.CubicMeterPerMeter), + (VolumePerLengthUnit.LiterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value / 1000, VolumePerLengthUnit.CubicMeterPerMeter), + (VolumePerLengthUnit.LiterPerMillimeter, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value, VolumePerLengthUnit.CubicMeterPerMeter), + (VolumePerLengthUnit.OilBarrelPerFoot, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value / 1.91713408, VolumePerLengthUnit.CubicMeterPerMeter), + + // BaseUnit -> VolumePerLengthUnit + (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerFoot) => new VolumePerLength(_value / 2.50838208, VolumePerLengthUnit.CubicYardPerFoot), + (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerUsSurveyFoot) => new VolumePerLength(_value / 2.50837706323584, VolumePerLengthUnit.CubicYardPerUsSurveyFoot), + (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerKilometer) => new VolumePerLength(_value * 1e6, VolumePerLengthUnit.LiterPerKilometer), + (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMeter) => new VolumePerLength(_value * 1000, VolumePerLengthUnit.LiterPerMeter), + (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMillimeter) => new VolumePerLength(_value, VolumePerLengthUnit.LiterPerMillimeter), + (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.OilBarrelPerFoot) => new VolumePerLength(_value * 1.91713408, VolumePerLengthUnit.OilBarrelPerFoot), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VolumePerLengthUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VolumePerLengthUnit> IQuantity<VolumePerLengthUnit>.ToUnit(VolumePerLengthUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VolumePerLengthUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(VolumePerLength)) + return this; + else if (conversionType == typeof(VolumePerLengthUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return VolumePerLength.Info; + else if (conversionType == typeof(BaseDimensions)) + return VolumePerLength.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLengthUnit.g.cs b/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLengthUnit.g.cs new file mode 100644 index 0000000000..73b3ab5b35 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumePerLength/VolumePerLengthUnit.g.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VolumePerLengthUnit + { + CubicMeterPerMeter = 1, + CubicYardPerFoot = 2, + CubicYardPerUsSurveyFoot = 3, + LiterPerKilometer = 4, + LiterPerMeter = 5, + LiterPerMillimeter = 6, + OilBarrelPerFoot = 7, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacity.csproj b/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacity.csproj new file mode 100644 index 0000000000..5a314da2f8 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacity.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET VolumetricHeatCapacity</Title> + <Description>Adds VolumetricHeatCapacity units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>volumetricheatcapacity unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{cd2b60c1-a4b5-36f2-afa3-6cf1031f9e7f}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.VolumetricHeatCapacity</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacity.g.cs b/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacity.g.cs new file mode 100644 index 0000000000..59b9bc42e4 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacity.g.cs @@ -0,0 +1,1009 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// The volumetric heat capacity is the amount of energy that must be added, in the form of heat, to one unit of volume of the material in order to cause an increase of one unit in its temperature. + /// </summary> + /// <remarks> + /// https://en.wikipedia.org/wiki/Volumetric_heat_capacity + /// </remarks> + [DataContract] + public readonly partial struct VolumetricHeatCapacity : IArithmeticQuantity<VolumetricHeatCapacity, VolumetricHeatCapacityUnit, double>, IEquatable<VolumetricHeatCapacity>, IComparable, IComparable<VolumetricHeatCapacity>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly VolumetricHeatCapacityUnit? _unit; + + static VolumetricHeatCapacity() + { + BaseDimensions = new BaseDimensions(-1, 1, -2, 0, -1, 0, 0); + BaseUnit = VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin; + Units = Enum.GetValues(typeof(VolumetricHeatCapacityUnit)).Cast<VolumetricHeatCapacityUnit>().ToArray(); + Zero = new VolumetricHeatCapacity(0, BaseUnit); + Info = new QuantityInfo<VolumetricHeatCapacityUnit>("VolumetricHeatCapacity", + new UnitInfo<VolumetricHeatCapacityUnit>[] + { + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, "BtusPerCubicFootDegreeFahrenheit", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, "CaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, "JoulesPerCubicMeterDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, "JoulesPerCubicMeterKelvin", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, "KilocaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, "KilojoulesPerCubicMeterDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, "KilojoulesPerCubicMeterKelvin", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, "MegajoulesPerCubicMeterDegreeCelsius", BaseUnits.Undefined), + new UnitInfo<VolumetricHeatCapacityUnit>(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MegajoulesPerCubicMeterKelvin", BaseUnits.Undefined), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public VolumetricHeatCapacity(double value, VolumetricHeatCapacityUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="VolumetricHeatCapacity" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<VolumetricHeatCapacityUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of VolumetricHeatCapacity, which is JoulePerCubicMeterKelvin. All conversions go via this value. + /// </summary> + public static VolumetricHeatCapacityUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the VolumetricHeatCapacity quantity. + /// </summary> + public static VolumetricHeatCapacityUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerCubicMeterKelvin. + /// </summary> + public static VolumetricHeatCapacity Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static VolumetricHeatCapacity AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public VolumetricHeatCapacityUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<VolumetricHeatCapacityUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => VolumetricHeatCapacity.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit"/> + /// </summary> + public double BtusPerCubicFootDegreeFahrenheit => As(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius"/> + /// </summary> + public double CaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius"/> + /// </summary> + public double JoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin"/> + /// </summary> + public double JoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius"/> + /// </summary> + public double KilocaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius"/> + /// </summary> + public double KilojoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin"/> + /// </summary> + public double KilojoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius"/> + /// </summary> + public double MegajoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin"/> + /// </summary> + public double MegajoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: VolumetricHeatCapacityUnit -> BaseUnit + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity); + + // Register in unit converter: BaseUnit -> VolumetricHeatCapacityUnit + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius)); + unitConverter.SetConversionFunction<VolumetricHeatCapacity>(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, new CultureInfo("en-US"), false, true, new string[]{"BTU/ft³·°F"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"cal/cm³·°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"J/m³·°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, new CultureInfo("en-US"), false, true, new string[]{"J/m³·K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"kcal/cm³·°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"kJ/m³·°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, new CultureInfo("en-US"), false, true, new string[]{"kJ/m³·K"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, new CultureInfo("en-US"), false, true, new string[]{"MJ/m³·°C"}); + unitAbbreviationsCache.PerformAbbreviationMapping(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, new CultureInfo("en-US"), false, true, new string[]{"MJ/m³·K"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(VolumetricHeatCapacityUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(VolumetricHeatCapacityUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(QuantityValue btuspercubicfootdegreefahrenheit) + { + double value = (double) btuspercubicfootdegreefahrenheit; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius(QuantityValue caloriespercubiccentimeterdegreecelsius) + { + double value = (double) caloriespercubiccentimeterdegreecelsius; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(QuantityValue joulespercubicmeterdegreecelsius) + { + double value = (double) joulespercubicmeterdegreecelsius; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(QuantityValue joulespercubicmeterkelvin) + { + double value = (double) joulespercubicmeterkelvin; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCelsius(QuantityValue kilocaloriespercubiccentimeterdegreecelsius) + { + double value = (double) kilocaloriespercubiccentimeterdegreecelsius; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(QuantityValue kilojoulespercubicmeterdegreecelsius) + { + double value = (double) kilojoulespercubicmeterdegreecelsius; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(QuantityValue kilojoulespercubicmeterkelvin) + { + double value = (double) kilojoulespercubicmeterkelvin; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(QuantityValue megajoulespercubicmeterdegreecelsius) + { + double value = (double) megajoulespercubicmeterdegreecelsius; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); + } + + /// <summary> + /// Creates a <see cref="VolumetricHeatCapacity"/> from <see cref="VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(QuantityValue megajoulespercubicmeterkelvin) + { + double value = (double) megajoulespercubicmeterkelvin; + return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="VolumetricHeatCapacityUnit" /> to <see cref="VolumetricHeatCapacity" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>VolumetricHeatCapacity unit value.</returns> + public static VolumetricHeatCapacity From(QuantityValue value, VolumetricHeatCapacityUnit fromUnit) + { + return new VolumetricHeatCapacity((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static VolumetricHeatCapacity Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static VolumetricHeatCapacity Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<VolumetricHeatCapacity, VolumetricHeatCapacityUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out VolumetricHeatCapacity result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out VolumetricHeatCapacity result) + { + return QuantityParser.Default.TryParse<VolumetricHeatCapacity, VolumetricHeatCapacityUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumetricHeatCapacityUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static VolumetricHeatCapacityUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<VolumetricHeatCapacityUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.VolumetricHeatCapacityUnit)"/> + public static bool TryParseUnit(string str, out VolumetricHeatCapacityUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out VolumetricHeatCapacityUnit unit) + { + return UnitParser.Default.TryParse<VolumetricHeatCapacityUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static VolumetricHeatCapacity operator -(VolumetricHeatCapacity right) + { + return new VolumetricHeatCapacity(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumetricHeatCapacity"/> from adding two <see cref="VolumetricHeatCapacity"/>.</summary> + public static VolumetricHeatCapacity operator +(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return new VolumetricHeatCapacity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumetricHeatCapacity"/> from subtracting two <see cref="VolumetricHeatCapacity"/>.</summary> + public static VolumetricHeatCapacity operator -(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return new VolumetricHeatCapacity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="VolumetricHeatCapacity"/> from multiplying value and <see cref="VolumetricHeatCapacity"/>.</summary> + public static VolumetricHeatCapacity operator *(double left, VolumetricHeatCapacity right) + { + return new VolumetricHeatCapacity(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="VolumetricHeatCapacity"/> from multiplying value and <see cref="VolumetricHeatCapacity"/>.</summary> + public static VolumetricHeatCapacity operator *(VolumetricHeatCapacity left, double right) + { + return new VolumetricHeatCapacity(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="VolumetricHeatCapacity"/> from dividing <see cref="VolumetricHeatCapacity"/> by value.</summary> + public static VolumetricHeatCapacity operator /(VolumetricHeatCapacity left, double right) + { + return new VolumetricHeatCapacity(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="VolumetricHeatCapacity"/> by <see cref="VolumetricHeatCapacity"/>.</summary> + public static double operator /(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.JoulesPerCubicMeterKelvin / right.JoulesPerCubicMeterKelvin; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="VolumetricHeatCapacity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumetricHeatCapacity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="VolumetricHeatCapacity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumetricHeatCapacity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumetricHeatCapacity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumetricHeatCapacity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is VolumetricHeatCapacity otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="VolumetricHeatCapacity"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(VolumetricHeatCapacity, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(VolumetricHeatCapacity other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="VolumetricHeatCapacity"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is VolumetricHeatCapacity otherQuantity)) throw new ArgumentException("Expected type VolumetricHeatCapacity.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="VolumetricHeatCapacity"/> with another <see cref="VolumetricHeatCapacity"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(VolumetricHeatCapacity other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another VolumetricHeatCapacity within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(VolumetricHeatCapacity other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current VolumetricHeatCapacity.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(VolumetricHeatCapacityUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is VolumetricHeatCapacityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this VolumetricHeatCapacity to another VolumetricHeatCapacity with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A VolumetricHeatCapacity with the specified unit.</returns> + public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="VolumetricHeatCapacity"/> to another <see cref="VolumetricHeatCapacity"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A VolumetricHeatCapacity with the specified unit.</returns> + public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(VolumetricHeatCapacity), Unit, typeof(VolumetricHeatCapacity), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (VolumetricHeatCapacity)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="VolumetricHeatCapacity"/> to another <see cref="VolumetricHeatCapacity"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="VolumetricHeatCapacity"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(VolumetricHeatCapacityUnit unit, [NotNullWhen(true)] out VolumetricHeatCapacity? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + VolumetricHeatCapacity? convertedOrNull = (Unit, unit) switch + { + // VolumetricHeatCapacityUnit -> BaseUnit + (VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity(_value / 1.4910660e-5, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity(_value / 2.388459e-7, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity(_value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value / 2.388459e-7) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e6d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e6d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), + + // BaseUnit -> VolumetricHeatCapacityUnit + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit) => new VolumetricHeatCapacity(_value * 1.4910660e-5, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius) => new VolumetricHeatCapacity(_value * 2.388459e-7, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius) => new VolumetricHeatCapacity(_value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius) => new VolumetricHeatCapacity((_value * 2.388459e-7) / 1e3d, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius) => new VolumetricHeatCapacity((_value) / 1e3d, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) / 1e3d, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius) => new VolumetricHeatCapacity((_value) / 1e6d, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius), + (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) / 1e6d, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is VolumetricHeatCapacityUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<VolumetricHeatCapacityUnit> IQuantity<VolumetricHeatCapacityUnit>.ToUnit(VolumetricHeatCapacityUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<VolumetricHeatCapacityUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(VolumetricHeatCapacity)) + return this; + else if (conversionType == typeof(VolumetricHeatCapacityUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return VolumetricHeatCapacity.Info; + else if (conversionType == typeof(BaseDimensions)) + return VolumetricHeatCapacity.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacityUnit.g.cs b/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacityUnit.g.cs new file mode 100644 index 0000000000..e3fb1141fb --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/VolumetricHeatCapacity/VolumetricHeatCapacityUnit.g.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum VolumetricHeatCapacityUnit + { + BtuPerCubicFootDegreeFahrenheit = 1, + CaloriePerCubicCentimeterDegreeCelsius = 2, + JoulePerCubicMeterDegreeCelsius = 3, + JoulePerCubicMeterKelvin = 4, + KilocaloriePerCubicCentimeterDegreeCelsius = 5, + KilojoulePerCubicMeterDegreeCelsius = 6, + KilojoulePerCubicMeterKelvin = 7, + MegajoulePerCubicMeterDegreeCelsius = 8, + MegajoulePerCubicMeterKelvin = 9, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertia.csproj b/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertia.csproj new file mode 100644 index 0000000000..ad6f1b7482 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertia.csproj @@ -0,0 +1,64 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.Duration</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET WarpingMomentOfInertia</Title> + <Description>Adds WarpingMomentOfInertia units for Units.NET.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>warpingmomentofinertia unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + <ProjectGuid>{8433aac6-218d-9b7b-6eaa-36774e165446}</ProjectGuid> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + <AssemblyName>UnitsNet.WarpingMomentOfInertia</AssemblyName> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> +<!-- <PackageReference Include="UnitsNet.Core" Version="" />--> + </ItemGroup> + + <!-- Project references that replace nuget dependencies while building. --> + <ItemGroup> + <ProjectReference Include="..\..\..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../../../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../../../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertia.g.cs b/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertia.g.cs new file mode 100644 index 0000000000..3355240e22 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertia.g.cs @@ -0,0 +1,943 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Runtime.Serialization; +using UnitsNet.InternalHelpers; +using UnitsNet.Units; + +#nullable enable + +// ReSharper disable once CheckNamespace + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// A geometric property of an area that is used to determine the warping stress. + /// </summary> + [DataContract] + public readonly partial struct WarpingMomentOfInertia : IArithmeticQuantity<WarpingMomentOfInertia, WarpingMomentOfInertiaUnit, double>, IEquatable<WarpingMomentOfInertia>, IComparable, IComparable<WarpingMomentOfInertia>, IConvertible, IFormattable + { + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + [DataMember(Name = "Value", Order = 0)] + private readonly double _value; + + /// <summary> + /// The unit this quantity was constructed with. + /// </summary> + [DataMember(Name = "Unit", Order = 1)] + private readonly WarpingMomentOfInertiaUnit? _unit; + + static WarpingMomentOfInertia() + { + BaseDimensions = new BaseDimensions(6, 0, 0, 0, 0, 0, 0); + BaseUnit = WarpingMomentOfInertiaUnit.MeterToTheSixth; + Units = Enum.GetValues(typeof(WarpingMomentOfInertiaUnit)).Cast<WarpingMomentOfInertiaUnit>().ToArray(); + Zero = new WarpingMomentOfInertia(0, BaseUnit); + Info = new QuantityInfo<WarpingMomentOfInertiaUnit>("WarpingMomentOfInertia", + new UnitInfo<WarpingMomentOfInertiaUnit>[] + { + new UnitInfo<WarpingMomentOfInertiaUnit>(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, "CentimetersToTheSixth", new BaseUnits(length: LengthUnit.Centimeter)), + new UnitInfo<WarpingMomentOfInertiaUnit>(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, "DecimetersToTheSixth", new BaseUnits(length: LengthUnit.Decimeter)), + new UnitInfo<WarpingMomentOfInertiaUnit>(WarpingMomentOfInertiaUnit.FootToTheSixth, "FeetToTheSixth", new BaseUnits(length: LengthUnit.Foot)), + new UnitInfo<WarpingMomentOfInertiaUnit>(WarpingMomentOfInertiaUnit.InchToTheSixth, "InchesToTheSixth", new BaseUnits(length: LengthUnit.Inch)), + new UnitInfo<WarpingMomentOfInertiaUnit>(WarpingMomentOfInertiaUnit.MeterToTheSixth, "MetersToTheSixth", new BaseUnits(length: LengthUnit.Meter)), + new UnitInfo<WarpingMomentOfInertiaUnit>(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "MillimetersToTheSixth", new BaseUnits(length: LengthUnit.Millimeter)), + }, + BaseUnit, Zero, BaseDimensions); + + DefaultConversionFunctions = new UnitConverter(); + RegisterDefaultConversions(DefaultConversionFunctions); + } + + /// <summary> + /// Creates the quantity with the given numeric value and unit. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="unit">The unit representation to construct this quantity with.</param> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public WarpingMomentOfInertia(double value, WarpingMomentOfInertiaUnit unit) + { + _value = Guard.EnsureValidNumber(value, nameof(value)); + _unit = unit; + } + + #region Static Properties + + /// <summary> + /// The <see cref="UnitConverter" /> containing the default generated conversion functions for <see cref="WarpingMomentOfInertia" /> instances. + /// </summary> + public static UnitConverter DefaultConversionFunctions { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + public static QuantityInfo<WarpingMomentOfInertiaUnit> Info { get; } + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public static BaseDimensions BaseDimensions { get; } + + /// <summary> + /// The base unit of WarpingMomentOfInertia, which is MeterToTheSixth. All conversions go via this value. + /// </summary> + public static WarpingMomentOfInertiaUnit BaseUnit { get; } + + /// <summary> + /// All units of measurement for the WarpingMomentOfInertia quantity. + /// </summary> + public static WarpingMomentOfInertiaUnit[] Units { get; } + + /// <summary> + /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheSixth. + /// </summary> + public static WarpingMomentOfInertia Zero { get; } + + /// <inheritdoc cref="Zero"/> + public static WarpingMomentOfInertia AdditiveIdentity => Zero; + + #endregion + + #region Properties + + /// <summary> + /// The numeric value this quantity was constructed with. + /// </summary> + public double Value => _value; + + /// <inheritdoc /> + QuantityValue IQuantity.Value => _value; + + Enum IQuantity.Unit => Unit; + + /// <inheritdoc /> + public WarpingMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); + + /// <inheritdoc /> + public QuantityInfo<WarpingMomentOfInertiaUnit> QuantityInfo => Info; + + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + QuantityInfo IQuantity.QuantityInfo => Info; + + /// <summary> + /// The <see cref="BaseDimensions" /> of this quantity. + /// </summary> + public BaseDimensions Dimensions => WarpingMomentOfInertia.BaseDimensions; + + #endregion + + #region Conversion Properties + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="WarpingMomentOfInertiaUnit.CentimeterToTheSixth"/> + /// </summary> + public double CentimetersToTheSixth => As(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="WarpingMomentOfInertiaUnit.DecimeterToTheSixth"/> + /// </summary> + public double DecimetersToTheSixth => As(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="WarpingMomentOfInertiaUnit.FootToTheSixth"/> + /// </summary> + public double FeetToTheSixth => As(WarpingMomentOfInertiaUnit.FootToTheSixth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="WarpingMomentOfInertiaUnit.InchToTheSixth"/> + /// </summary> + public double InchesToTheSixth => As(WarpingMomentOfInertiaUnit.InchToTheSixth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="WarpingMomentOfInertiaUnit.MeterToTheSixth"/> + /// </summary> + public double MetersToTheSixth => As(WarpingMomentOfInertiaUnit.MeterToTheSixth); + + /// <summary> + /// Gets a <see cref="double"/> value of this quantity converted into <see cref="WarpingMomentOfInertiaUnit.MillimeterToTheSixth"/> + /// </summary> + public double MillimetersToTheSixth => As(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); + + #endregion + + #region Static Methods + + /// <summary> + /// Registers the default conversion functions in the given <see cref="UnitConverter"/> instance. + /// </summary> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to register the default conversion functions in.</param> + internal static void RegisterDefaultConversions(UnitConverter unitConverter) + { + // Register in unit converter: WarpingMomentOfInertiaUnit -> BaseUnit + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.FootToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.InchToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity); + + // Register in unit converter: BaseUnit -> WarpingMomentOfInertiaUnit + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.CentimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.CentimeterToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.DecimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.DecimeterToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.FootToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.FootToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.InchToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.InchToTheSixth)); + unitConverter.SetConversionFunction<WarpingMomentOfInertia>(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MillimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MillimeterToTheSixth)); + } + + internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) + { + unitAbbreviationsCache.PerformAbbreviationMapping(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, new CultureInfo("en-US"), false, true, new string[]{"cm⁶", "cm^6"}); + unitAbbreviationsCache.PerformAbbreviationMapping(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, new CultureInfo("en-US"), false, true, new string[]{"dm⁶", "dm^6"}); + unitAbbreviationsCache.PerformAbbreviationMapping(WarpingMomentOfInertiaUnit.FootToTheSixth, new CultureInfo("en-US"), false, true, new string[]{"ft⁶", "ft^6"}); + unitAbbreviationsCache.PerformAbbreviationMapping(WarpingMomentOfInertiaUnit.InchToTheSixth, new CultureInfo("en-US"), false, true, new string[]{"in⁶", "in^6"}); + unitAbbreviationsCache.PerformAbbreviationMapping(WarpingMomentOfInertiaUnit.MeterToTheSixth, new CultureInfo("en-US"), false, true, new string[]{"m⁶", "m^6"}); + unitAbbreviationsCache.PerformAbbreviationMapping(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, new CultureInfo("en-US"), false, true, new string[]{"mm⁶", "mm^6"}); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit) + { + return GetAbbreviation(unit, null); + } + + /// <summary> + /// Get unit abbreviation string. + /// </summary> + /// <param name="unit">Unit to get abbreviation for.</param> + /// <returns>Unit abbreviation string.</returns> + /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit, IFormatProvider? provider) + { + return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// <summary> + /// Creates a <see cref="WarpingMomentOfInertia"/> from <see cref="WarpingMomentOfInertiaUnit.CentimeterToTheSixth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static WarpingMomentOfInertia FromCentimetersToTheSixth(QuantityValue centimeterstothesixth) + { + double value = (double) centimeterstothesixth; + return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.CentimeterToTheSixth); + } + + /// <summary> + /// Creates a <see cref="WarpingMomentOfInertia"/> from <see cref="WarpingMomentOfInertiaUnit.DecimeterToTheSixth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static WarpingMomentOfInertia FromDecimetersToTheSixth(QuantityValue decimeterstothesixth) + { + double value = (double) decimeterstothesixth; + return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.DecimeterToTheSixth); + } + + /// <summary> + /// Creates a <see cref="WarpingMomentOfInertia"/> from <see cref="WarpingMomentOfInertiaUnit.FootToTheSixth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static WarpingMomentOfInertia FromFeetToTheSixth(QuantityValue feettothesixth) + { + double value = (double) feettothesixth; + return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.FootToTheSixth); + } + + /// <summary> + /// Creates a <see cref="WarpingMomentOfInertia"/> from <see cref="WarpingMomentOfInertiaUnit.InchToTheSixth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static WarpingMomentOfInertia FromInchesToTheSixth(QuantityValue inchestothesixth) + { + double value = (double) inchestothesixth; + return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.InchToTheSixth); + } + + /// <summary> + /// Creates a <see cref="WarpingMomentOfInertia"/> from <see cref="WarpingMomentOfInertiaUnit.MeterToTheSixth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static WarpingMomentOfInertia FromMetersToTheSixth(QuantityValue meterstothesixth) + { + double value = (double) meterstothesixth; + return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MeterToTheSixth); + } + + /// <summary> + /// Creates a <see cref="WarpingMomentOfInertia"/> from <see cref="WarpingMomentOfInertiaUnit.MillimeterToTheSixth"/>. + /// </summary> + /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> + public static WarpingMomentOfInertia FromMillimetersToTheSixth(QuantityValue millimeterstothesixth) + { + double value = (double) millimeterstothesixth; + return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MillimeterToTheSixth); + } + + /// <summary> + /// Dynamically convert from value and unit enum <see cref="WarpingMomentOfInertiaUnit" /> to <see cref="WarpingMomentOfInertia" />. + /// </summary> + /// <param name="value">Value to convert from.</param> + /// <param name="fromUnit">Unit to convert from.</param> + /// <returns>WarpingMomentOfInertia unit value.</returns> + public static WarpingMomentOfInertia From(QuantityValue value, WarpingMomentOfInertiaUnit fromUnit) + { + return new WarpingMomentOfInertia((double)value, fromUnit); + } + + #endregion + + #region Static Parse Methods + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + public static WarpingMomentOfInertia Parse(string str) + { + return Parse(str, null); + } + + /// <summary> + /// Parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="ArgumentException"> + /// Expected string to have one or two pairs of quantity and unit in the format + /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" + /// </exception> + /// <exception cref="AmbiguousUnitParseException"> + /// More than one unit is represented by the specified unit abbreviation. + /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of + /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. + /// </exception> + /// <exception cref="UnitsNetException"> + /// If anything else goes wrong, typically due to a bug or unhandled case. + /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish + /// Units.NET exceptions from other exceptions. + /// </exception> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static WarpingMomentOfInertia Parse(string str, IFormatProvider? provider) + { + return QuantityParser.Default.Parse<WarpingMomentOfInertia, WarpingMomentOfInertiaUnit>( + str, + provider, + From); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + public static bool TryParse(string? str, out WarpingMomentOfInertia result) + { + return TryParse(str, null, out result); + } + + /// <summary> + /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="result">Resulting unit quantity if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.Parse("5.5 m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParse(string? str, IFormatProvider? provider, out WarpingMomentOfInertia result) + { + return QuantityParser.Default.TryParse<WarpingMomentOfInertia, WarpingMomentOfInertiaUnit>( + str, + provider, + From, + out result); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static WarpingMomentOfInertiaUnit ParseUnit(string str) + { + return ParseUnit(str, null); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <example> + /// Length.ParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> + /// <exception cref="UnitsNetException">Error parsing string.</exception> + public static WarpingMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse<WarpingMomentOfInertiaUnit>(str, provider); + } + + /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.WarpingMomentOfInertiaUnit)"/> + public static bool TryParseUnit(string str, out WarpingMomentOfInertiaUnit unit) + { + return TryParseUnit(str, null, out unit); + } + + /// <summary> + /// Parse a unit string. + /// </summary> + /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> + /// <param name="unit">The parsed unit if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + /// <example> + /// Length.TryParseUnit("m", new CultureInfo("en-US")); + /// </example> + /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public static bool TryParseUnit(string str, IFormatProvider? provider, out WarpingMomentOfInertiaUnit unit) + { + return UnitParser.Default.TryParse<WarpingMomentOfInertiaUnit>(str, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// <summary>Negate the value.</summary> + public static WarpingMomentOfInertia operator -(WarpingMomentOfInertia right) + { + return new WarpingMomentOfInertia(-right.Value, right.Unit); + } + + /// <summary>Get <see cref="WarpingMomentOfInertia"/> from adding two <see cref="WarpingMomentOfInertia"/>.</summary> + public static WarpingMomentOfInertia operator +(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return new WarpingMomentOfInertia(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="WarpingMomentOfInertia"/> from subtracting two <see cref="WarpingMomentOfInertia"/>.</summary> + public static WarpingMomentOfInertia operator -(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return new WarpingMomentOfInertia(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// <summary>Get <see cref="WarpingMomentOfInertia"/> from multiplying value and <see cref="WarpingMomentOfInertia"/>.</summary> + public static WarpingMomentOfInertia operator *(double left, WarpingMomentOfInertia right) + { + return new WarpingMomentOfInertia(left * right.Value, right.Unit); + } + + /// <summary>Get <see cref="WarpingMomentOfInertia"/> from multiplying value and <see cref="WarpingMomentOfInertia"/>.</summary> + public static WarpingMomentOfInertia operator *(WarpingMomentOfInertia left, double right) + { + return new WarpingMomentOfInertia(left.Value * right, left.Unit); + } + + /// <summary>Get <see cref="WarpingMomentOfInertia"/> from dividing <see cref="WarpingMomentOfInertia"/> by value.</summary> + public static WarpingMomentOfInertia operator /(WarpingMomentOfInertia left, double right) + { + return new WarpingMomentOfInertia(left.Value / right, left.Unit); + } + + /// <summary>Get ratio value from dividing <see cref="WarpingMomentOfInertia"/> by <see cref="WarpingMomentOfInertia"/>.</summary> + public static double operator /(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.MetersToTheSixth / right.MetersToTheSixth; + } + + #endregion + + #region Equality / IComparable + + /// <summary>Returns true if less or equal to.</summary> + public static bool operator <=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than or equal to.</summary> + public static bool operator >=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if less than.</summary> + public static bool operator <(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// <summary>Returns true if greater than.</summary> + public static bool operator >(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.Value > right.ToUnit(left.Unit).Value; + } + + // We use obsolete attribute to communicate the preferred equality members to use. + // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. + #pragma warning disable CS0809 + + /// <summary>Indicates strict equality of two <see cref="WarpingMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(WarpingMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator ==(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return left.Equals(right); + } + + /// <summary>Indicates strict inequality of two <see cref="WarpingMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(WarpingMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public static bool operator !=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) + { + return !(left == right); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="WarpingMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(WarpingMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public override bool Equals(object? obj) + { + if (obj is null || !(obj is WarpingMomentOfInertia otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// <inheritdoc /> + /// <summary>Indicates strict equality of two <see cref="WarpingMomentOfInertia"/> quantities, where both <see cref="Value" /> and <see cref="Unit" /> are exactly equal.</summary> + /// <remarks>Consider using <see cref="Equals(WarpingMomentOfInertia, double, ComparisonType)"/> to check equality across different units and to specify a floating-point number error tolerance.</remarks> + [Obsolete("Consider using Equals(Angle, double, ComparisonType) to check equality across different units and to specify a floating-point number error tolerance.")] + public bool Equals(WarpingMomentOfInertia other) + { + return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + } + + #pragma warning restore CS0809 + + /// <summary>Compares the current <see cref="WarpingMomentOfInertia"/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="obj">An object to compare with this instance.</param> + /// <exception cref="T:System.ArgumentException"> + /// <paramref name="obj" /> is not the same type as this instance. + /// </exception> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="obj" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="obj" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="obj" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(object? obj) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + if (!(obj is WarpingMomentOfInertia otherQuantity)) throw new ArgumentException("Expected type WarpingMomentOfInertia.", nameof(obj)); + + return CompareTo(otherQuantity); + } + + /// <summary>Compares the current <see cref="WarpingMomentOfInertia"/> with another <see cref="WarpingMomentOfInertia"/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary> + /// <param name="other">A quantity to compare with this instance.</param> + /// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings: + /// <list type="table"> + /// <listheader><term> Value</term><description> Meaning</description></listheader> + /// <item><term> Less than zero</term><description> This instance precedes <paramref name="other" /> in the sort order.</description></item> + /// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name="other" />.</description></item> + /// <item><term> Greater than zero</term><description> This instance follows <paramref name="other" /> in the sort order.</description></item> + /// </list> + /// </returns> + public int CompareTo(WarpingMomentOfInertia other) + { + return _value.CompareTo(other.ToUnit(this.Unit).Value); + } + + /// <summary> + /// <para> + /// Compare equality to another WarpingMomentOfInertia within the given absolute or relative tolerance. + /// </para> + /// <para> + /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of + /// this quantity's value to be considered equal. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Relative); + /// </code> + /// </example> + /// </para> + /// <para> + /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and + /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into + /// this quantity's unit for comparison. + /// <example> + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// <code> + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromInches(50.0); + /// a.Equals(b, 0.01, ComparisonType.Absolute); + /// </code> + /// </example> + /// </para> + /// <para> + /// Note that it is advised against specifying zero difference, due to the nature + /// of floating-point operations and using double internally. + /// </para> + /// </summary> + /// <param name="other">The other quantity to compare to.</param> + /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> + /// <param name="comparisonType">The comparison type: either relative or absolute.</param> + /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> + public bool Equals(WarpingMomentOfInertia other, double tolerance, ComparisonType comparisonType) + { + if (tolerance < 0) + throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); + + double thisValue = this.Value; + double otherValueInThisUnits = other.As(this.Unit); + + return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); + } + + /// <summary> + /// Returns the hash code for this instance. + /// </summary> + /// <returns>A hash code for the current WarpingMomentOfInertia.</returns> + public override int GetHashCode() + { + return new { Info.Name, Value, Unit }.GetHashCode(); + } + + #endregion + + #region Conversion Methods + + /// <summary> + /// Convert to the unit representation <paramref name="unit" />. + /// </summary> + /// <returns>Value converted to the specified unit.</returns> + public double As(WarpingMomentOfInertiaUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// <inheritdoc /> + double IQuantity.As(Enum unit) + { + if (!(unit is WarpingMomentOfInertiaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return (double)As(typedUnit); + } + + /// <summary> + /// Converts this WarpingMomentOfInertia to another WarpingMomentOfInertia with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <returns>A WarpingMomentOfInertia with the specified unit.</returns> + public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit) + { + return ToUnit(unit, DefaultConversionFunctions); + } + + /// <summary> + /// Converts this <see cref="WarpingMomentOfInertia"/> to another <see cref="WarpingMomentOfInertia"/> using the given <paramref name="unitConverter"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="unitConverter">The <see cref="UnitConverter"/> to use for the conversion.</param> + /// <returns>A WarpingMomentOfInertia with the specified unit.</returns> + public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit, UnitConverter unitConverter) + { + if (TryToUnit(unit, out var converted)) + { + // Try to convert using the auto-generated conversion methods. + return converted!.Value; + } + else if (unitConverter.TryGetConversionFunction((typeof(WarpingMomentOfInertia), Unit, typeof(WarpingMomentOfInertia), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (WarpingMomentOfInertia)conversionFunction(this); + } + else if (Unit != BaseUnit) + { + // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. + var inBaseUnits = ToUnit(BaseUnit); + return inBaseUnits.ToUnit(unit); + } + else + { + // No possible conversion + throw new NotImplementedException($"Can not convert {Unit} to {unit}."); + } + } + + /// <summary> + /// Attempts to convert this <see cref="WarpingMomentOfInertia"/> to another <see cref="WarpingMomentOfInertia"/> with the unit representation <paramref name="unit" />. + /// </summary> + /// <param name="unit">The unit to convert to.</param> + /// <param name="converted">The converted <see cref="WarpingMomentOfInertia"/> in <paramref name="unit"/>, if successful.</param> + /// <returns>True if successful, otherwise false.</returns> + private bool TryToUnit(WarpingMomentOfInertiaUnit unit, [NotNullWhen(true)] out WarpingMomentOfInertia? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + WarpingMomentOfInertia? convertedOrNull = (Unit, unit) switch + { + // WarpingMomentOfInertiaUnit -> BaseUnit + (WarpingMomentOfInertiaUnit.CentimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value / 1e12, WarpingMomentOfInertiaUnit.MeterToTheSixth), + (WarpingMomentOfInertiaUnit.DecimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value / 1e6, WarpingMomentOfInertiaUnit.MeterToTheSixth), + (WarpingMomentOfInertiaUnit.FootToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value * Math.Pow(0.3048, 6), WarpingMomentOfInertiaUnit.MeterToTheSixth), + (WarpingMomentOfInertiaUnit.InchToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value * Math.Pow(2.54e-2, 6), WarpingMomentOfInertiaUnit.MeterToTheSixth), + (WarpingMomentOfInertiaUnit.MillimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value / 1e18, WarpingMomentOfInertiaUnit.MeterToTheSixth), + + // BaseUnit -> WarpingMomentOfInertiaUnit + (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.CentimeterToTheSixth) => new WarpingMomentOfInertia(_value * 1e12, WarpingMomentOfInertiaUnit.CentimeterToTheSixth), + (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.DecimeterToTheSixth) => new WarpingMomentOfInertia(_value * 1e6, WarpingMomentOfInertiaUnit.DecimeterToTheSixth), + (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.FootToTheSixth) => new WarpingMomentOfInertia(_value / Math.Pow(0.3048, 6), WarpingMomentOfInertiaUnit.FootToTheSixth), + (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.InchToTheSixth) => new WarpingMomentOfInertia(_value / Math.Pow(2.54e-2, 6), WarpingMomentOfInertiaUnit.InchToTheSixth), + (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MillimeterToTheSixth) => new WarpingMomentOfInertia(_value * 1e18, WarpingMomentOfInertiaUnit.MillimeterToTheSixth), + + _ => null + }; + + if (convertedOrNull is null) + { + converted = default; + return false; + } + + converted = convertedOrNull.Value; + return true; + } + + /// <inheritdoc /> + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is WarpingMomentOfInertiaUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// <inheritdoc /> + IQuantity<WarpingMomentOfInertiaUnit> IQuantity<WarpingMomentOfInertiaUnit>.ToUnit(WarpingMomentOfInertiaUnit unit) => ToUnit(unit); + + #endregion + + #region ToString Methods + + /// <summary> + /// Gets the default string representation of value and unit. + /// </summary> + /// <returns>String representation.</returns> + public override string ToString() + { + return ToString("g"); + } + + /// <summary> + /// Gets the default string representation of value and unit using the given format provider. + /// </summary> + /// <returns>String representation.</returns> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + public string ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentCulture" />. + /// </summary> + /// <param name="format">The format string.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> + /// <summary> + /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentCulture" /> if null. + /// </summary> + /// <param name="format">The format string.</param> + /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentCulture" /> if null.</param> + /// <returns>The string representation.</returns> + public string ToString(string? format, IFormatProvider? provider) + { + return QuantityFormatter.Format<WarpingMomentOfInertiaUnit>(this, format, provider); + } + + #endregion + + #region IConvertible Methods + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to bool is not supported."); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return Convert.ToByte(_value); + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to char is not supported."); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to DateTime is not supported."); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(_value); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return Convert.ToDouble(_value); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(_value); + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(_value); + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(_value); + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(_value); + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(_value); + } + + string IConvertible.ToString(IFormatProvider? provider) + { + return ToString("g", provider); + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == typeof(WarpingMomentOfInertia)) + return this; + else if (conversionType == typeof(WarpingMomentOfInertiaUnit)) + return Unit; + else if (conversionType == typeof(QuantityInfo)) + return WarpingMomentOfInertia.Info; + else if (conversionType == typeof(BaseDimensions)) + return WarpingMomentOfInertia.BaseDimensions; + else + throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to {conversionType} is not supported."); + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(_value); + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(_value); + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(_value); + } + + #endregion + } +} diff --git a/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertiaUnit.g.cs b/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertiaUnit.g.cs new file mode 100644 index 0000000000..5f77a6d521 --- /dev/null +++ b/UnitsNet.Modular/GeneratedCode/WarpingMomentOfInertia/WarpingMomentOfInertiaUnit.g.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// </auto-generated> +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum WarpingMomentOfInertiaUnit + { + CentimeterToTheSixth = 1, + DecimeterToTheSixth = 2, + FootToTheSixth = 3, + InchToTheSixth = 4, + MeterToTheSixth = 5, + MillimeterToTheSixth = 6, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs b/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs index 6f38f65936..f031ebd046 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs +++ b/UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs @@ -24,7 +24,7 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("CUnitsNet")] +[assembly: AssemblyTitle("UnitsNet")] [assembly: AssemblyDescription("Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Andreas Gullberg Larsen")] diff --git a/UnitsNet.SI/BaseUnits.cs b/UnitsNet.SI/BaseUnits.cs new file mode 100644 index 0000000000..0c7eb68bac --- /dev/null +++ b/UnitsNet.SI/BaseUnits.cs @@ -0,0 +1,197 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Text; + +namespace UnitsNet +{ + /// <inheritdoc /> + /// <summary> + /// Represents the base units for a quantity. All quantities, both base and derived, can be + /// represented by a combination of these seven base units. + /// </summary> + public sealed class BaseUnits: IEquatable<BaseUnits> + { + /// <summary> + /// Represents BaseUnits that have not been defined. + /// </summary> + public static BaseUnits Undefined { get; } = new BaseUnits(); + + /// <summary> + /// Creates an instance of if the base units class that represents the base units for a quantity. + /// All quantities, both base and derived, can be represented by a combination of these seven base units. + /// </summary> + /// <param name="length">The length unit (L).</param> + /// <param name="mass">The mass unit (M).</param> + /// <param name="time">The time unit (T).</param> + /// <param name="current">The electric current unit (I).</param> + /// <param name="temperature">The temperature unit (Θ).</param> + /// <param name="amount">The amount of substance unit (N).</param> + /// <param name="luminousIntensity">The luminous intensity unit (J).</param> + public BaseUnits( + Enum? length = null, + Enum? mass = null, + Enum? time = null, + Enum? current = null, + Enum? temperature = null, + Enum? amount = null, + Enum? luminousIntensity = null) + { + Length = length; + Mass = mass; + Time = time; + Current = current; + Temperature = temperature; + Amount = amount; + LuminousIntensity = luminousIntensity; + + IsFullyDefined = Length is not null && + Mass is not null & + Time is not null && + Current is not null && + Temperature is not null && + Amount is not null && + LuminousIntensity is not null; + } + + /// <inheritdoc /> + public override bool Equals(object? obj) + { + return obj is BaseUnits other && Equals(other); + } + + /// <summary> + /// Checks if all of the base units are equal to another instance's. + /// </summary> + /// <param name="other">The other instance to check if equal to.</param> + /// <returns>True if equal, otherwise false.</returns> + public bool Equals(BaseUnits? other) + { + if (other is null) + return false; + + return Equals(Length, other.Length) && + Equals(Mass, other.Mass) && + Equals(Time, other.Time) && + Equals(Current, other.Current) && + Equals(Temperature, other.Temperature) && + Equals(Amount, other.Amount) && + Equals(LuminousIntensity, other.LuminousIntensity); + } + + /// <summary> + /// Checks if the base units are a subset of another. Undefined base units are ignored. + /// If all base united are undefined (equal to <see cref="BaseUnits.Undefined"/>), + /// IsSubsetOf will return true only if other is also equal to <see cref="BaseUnits.Undefined"/>. + /// </summary> + /// <param name="other">The other <see cref="BaseUnits"/> to compare to.</param> + /// <returns>True if the base units are a subset of other, otherwise false.</returns> + public bool IsSubsetOf(BaseUnits other) + { + if (other == null) throw new ArgumentNullException(nameof(other)); + + // If all base units are undefined, can only be a subset of another where all base units are undefined. + if (Equals(Undefined)) + return other.Equals(Undefined); + + return (Length == null || Equals(Length, other.Length)) && + (Mass == null || Equals(Mass, other.Mass)) && + (Time == null || Equals(Time, other.Time)) && + (Current == null || Equals(Current, other.Current)) && + (Temperature == null || Equals(Temperature, other.Temperature)) && + (Amount == null || Equals(Amount, other.Amount)) && + (LuminousIntensity == null || Equals(LuminousIntensity, other.LuminousIntensity)); + } + + /// <inheritdoc /> + public override int GetHashCode() + { + return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); + } + + /// <summary> + /// Checks if this instance is equal to another. + /// </summary> + /// <param name="left">The left instance.</param> + /// <param name="right">The right instance.</param> + /// <returns>True if equal, otherwise false.</returns> + /// <seealso cref="Equals(BaseUnits)"/> + public static bool operator ==(BaseUnits? left, BaseUnits? right) + { + return left?.Equals(right!) ?? right is null; + } + + /// <summary> + /// Checks if this instance is not equal to another. + /// </summary> + /// <param name="left">The left instance.</param> + /// <param name="right">The right instance.</param> + /// <returns>True if not equal, otherwise false.</returns> + /// <seealso cref="Equals(BaseUnits)"/> + public static bool operator !=(BaseUnits? left, BaseUnits? right) + { + return !(left == right); + } + + /// <inheritdoc /> + public override string ToString() + { + var sb = new StringBuilder(); + + string GetDefaultAbbreviation(Enum? unitOrNull) => unitOrNull is { } unit + ? UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit) + : "N/A"; + + sb.AppendFormat("[Length]: {0}, ", GetDefaultAbbreviation(Length)); + sb.AppendFormat("[Mass]: {0}, ", GetDefaultAbbreviation(Mass)); + sb.AppendFormat("[Time]: {0}, ", GetDefaultAbbreviation(Time)); + sb.AppendFormat("[Current]: {0}, ", GetDefaultAbbreviation(Current)); + sb.AppendFormat("[Temperature]: {0}, ", GetDefaultAbbreviation(Temperature)); + sb.AppendFormat("[Amount]: {0}, ", GetDefaultAbbreviation(Amount)); + sb.AppendFormat("[LuminousIntensity]: {0}", GetDefaultAbbreviation(LuminousIntensity)); + + return sb.ToString(); + } + + /// <summary> + /// Gets the length unit (L). + /// </summary> + public Enum? Length { get; } + + /// <summary> + /// Gets the mass unit (M). + /// </summary> + public Enum? Mass{ get; } + + /// <summary> + /// Gets the time unit (T). + /// </summary> + public Enum? Time{ get; } + + /// <summary> + /// Gets the electric current unit (I). + /// </summary> + public Enum? Current{ get; } + + /// <summary> + /// Gets the temperature unit (Θ). + /// </summary> + public Enum? Temperature{ get; } + + /// <summary> + /// Gets the amount of substance unit (N). + /// </summary> + public Enum? Amount{ get; } + + /// <summary> + /// Gets the luminous intensity unit (J). + /// </summary> + public Enum? LuminousIntensity{ get; } + + /// <summary> + /// Gets whether or not all of the base units are defined. + /// </summary> + public bool IsFullyDefined { get; } + } +} diff --git a/UnitsNet.SI/UnitSystem.cs b/UnitsNet.SI/UnitSystem.cs new file mode 100644 index 0000000000..ecb539cf04 --- /dev/null +++ b/UnitsNet.SI/UnitSystem.cs @@ -0,0 +1,103 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Linq; + +namespace UnitsNet +{ + /// <summary> + /// A unit system defined by a combination of base units. + /// This is typically used to define the "working units" for consistently creating and presenting quantities in the selected base units, + /// such as <see cref="SI"/> to use SI base units such as meters, kilograms and seconds. + /// </summary> + public sealed class UnitSystem : IEquatable<UnitSystem> + { + /// <summary> + /// Creates an instance of a unit system with the specified base units. + /// </summary> + /// <param name="baseUnits">The base units for the unit system.</param> + public UnitSystem(BaseUnits baseUnits) + { + if (baseUnits is null) throw new ArgumentNullException(nameof(baseUnits)); + if (!baseUnits.IsFullyDefined) throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); + + BaseUnits = baseUnits; + } + + /// <summary> + /// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>. + /// If multiple compatible units were found, the first match is used. + /// </summary> + /// <param name="value">The numeric value to construct this quantity with.</param> + /// <param name="quantityInfo">Information about the quantity type to create.</param> + /// <exception cref="ArgumentNullException">The given <see cref="QuantityInfo"/> is null.</exception> + /// <exception cref="InvalidOperationException">No unit was found for the given <see cref="UnitSystem"/>.</exception> + public IQuantity CreateQuantity(QuantityInfo quantityInfo, double value) + { + if (quantityInfo == null) throw new ArgumentNullException(nameof(quantityInfo)); + + var unitInfos = quantityInfo.GetUnitInfosFor(BaseUnits); + UnitInfo firstUnitInfo = unitInfos.FirstOrDefault() ?? + throw new InvalidOperationException($"No {quantityInfo.Name} units were found for unit system with base units {BaseUnits}."); + + Enum unit = firstUnitInfo.Value; + return quantityInfo.CreateQuantity(value, unit); + } + + /// <inheritdoc /> + public override bool Equals(object? other) + { + return other is UnitSystem otherUnitSystem && Equals(otherUnitSystem); + } + + /// <inheritdoc /> + public bool Equals(UnitSystem? other) + { + return other is not null && BaseUnits.Equals(other.BaseUnits); + } + + /// <summary> + /// Checks if this instance is equal to another. + /// </summary> + /// <param name="left">The left instance.</param> + /// <param name="right">The right instance.</param> + /// <returns>True if equal, otherwise false.</returns> + /// <seealso cref="Equals(UnitSystem)"/> + public static bool operator ==(UnitSystem? left, UnitSystem? right) + { + return left?.Equals(right) ?? right is null; + } + + /// <summary> + /// Checks if this instance is equal to another. + /// </summary> + /// <param name="left">The left instance.</param> + /// <param name="right">The right instance.</param> + /// <returns>True if equal, otherwise false.</returns> + /// <seealso cref="Equals(UnitSystem)"/> + public static bool operator !=(UnitSystem? left, UnitSystem? right) + { + return !(left == right); + } + + /// <inheritdoc /> + public override int GetHashCode() + { + return new {BaseUnits}.GetHashCode(); + } + + /// <summary> + /// The base units of this unit system. + /// </summary> + public BaseUnits BaseUnits{ get; } + + private static readonly BaseUnits SIBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + /// <summary> + /// Gets the SI unit system. + /// </summary> + public static UnitSystem SI { get; } = new UnitSystem(SIBaseUnits); + } +} diff --git a/UnitsNet.SI/UnitSystemIQuantityExtensions.cs b/UnitsNet.SI/UnitSystemIQuantityExtensions.cs new file mode 100644 index 0000000000..eaa25aa7f2 --- /dev/null +++ b/UnitsNet.SI/UnitSystemIQuantityExtensions.cs @@ -0,0 +1,135 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UnitsNet; + +/// <summary> +/// Extension methods for <see cref="IQuantity" /> to add support for conversions involving UnitSystem. +/// </summary> +public static class UnitSystemIQuantityExtensions +{ + /// <summary> + /// Converts to a quantity with a unit determined by the given <see cref="UnitSystem"/>, which affects things like <see cref="IQuantity.ToString(System.IFormatProvider)"/>. + /// If multiple units were found for the given <see cref="UnitSystem"/>, the first match will be used. + /// </summary> + /// <param name="quantity">The quantity.</param> + /// <param name="unitSystem">The <see cref="UnitSystem"/> to convert the quantity to.</param> + /// <returns>A new quantity with the determined unit.</returns> + public static TQuantity ToUnit<TQuantity>(this TQuantity quantity, UnitSystem unitSystem) + where TQuantity : IQuantity + { + if (unitSystem == null) throw new ArgumentNullException(nameof(unitSystem)); + + Enum unitEnumValue = GetUnitEnumValue(quantity, unitSystem); + + return (TQuantity)quantity.ToUnit(unitEnumValue); + } + + /// <summary> + /// Converts to a quantity with a unit determined by the given <see cref="UnitSystem"/>, which affects things like <see cref="IQuantity.ToString(System.IFormatProvider)"/>. + /// If multiple units were found for the given <see cref="UnitSystem"/>, the first match will be used. + /// </summary> + /// <param name="quantity">The quantity.</param> + /// <param name="unitSystem">The <see cref="UnitSystem"/> to convert the quantity to.</param> + /// <returns>A new quantity with the determined unit.</returns> + public static IQuantity ToUnit(this IQuantity quantity, UnitSystem unitSystem) + { + if (unitSystem == null) throw new ArgumentNullException(nameof(unitSystem)); + + Enum unitEnumValue = GetUnitEnumValue(quantity, unitSystem); + + return quantity.ToUnit(unitEnumValue); + } + + /// <summary> + /// Gets the value in the unit determined by the given <see cref="UnitSystem" />. If multiple units were found for the + /// given <see cref="UnitSystem" />, + /// the first match will be used. + /// </summary> + /// <param name="quantity">The quantity.</param> + /// <param name="unitSystem">The <see cref="UnitSystem" /> to convert the quantity value to.</param> + /// <returns>The converted value.</returns> + public static double As(this IQuantity quantity, UnitSystem unitSystem) + { + if (unitSystem == null) throw new ArgumentNullException(nameof(unitSystem)); + + Enum unitEnumValue = GetUnitEnumValue(quantity, unitSystem); + return quantity.As(unitEnumValue); + } + + /// <summary> + /// Gets the unit enum value for the given quantity as configured by the SI base units in the given unit system. + /// </summary> + /// <param name="quantity">The quantity.</param> + /// <param name="unitSystem">The unit system with configured SI base units.</param> + /// <returns></returns> + /// <exception cref="ArgumentNullException">quantity or unitSystem was null.</exception> + /// <exception cref="ArgumentException">No units were found for the given UnitSystem.</exception> + public static Enum GetUnitEnumValue(this IQuantity quantity, UnitSystem unitSystem) + { + if (quantity == null) throw new ArgumentNullException(nameof(quantity)); + if (unitSystem == null) throw new ArgumentNullException(nameof(unitSystem)); + + IEnumerable<UnitInfo> unitInfos = GetUnitInfosFor(quantity.QuantityInfo, unitSystem.BaseUnits); + + UnitInfo firstUnitInfo = unitInfos.FirstOrDefault() + ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); + + return firstUnitInfo.Value; + } + + /// <summary> + /// Gets an <see cref="IEnumerable{T}" /> of <see cref="UnitInfo" /> that have <see cref="BaseUnits" /> that is a + /// subset of <paramref name="baseUnits" />. + /// </summary> + /// <param name="quantityInfo">The quantity info.</param> + /// <param name="baseUnits">The <see cref="BaseUnits" /> to check against.</param> + /// <returns> + /// An <see cref="IEnumerable{T}" /> of <see cref="UnitInfo" /> that have <see cref="BaseUnits" /> that is a + /// subset of <paramref name="baseUnits" />. + /// </returns> + /// <exception cref="ArgumentNullException"><paramref name="baseUnits" /> is null.</exception> + public static IEnumerable<UnitInfo> GetUnitInfosFor(this QuantityInfo quantityInfo, BaseUnits baseUnits) + { + if (baseUnits is null) + { + throw new ArgumentNullException(nameof(baseUnits)); + } + + return quantityInfo.UnitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); + } + + /// <summary> + /// Gets the <see cref="UnitInfo"/> whose <see cref="BaseUnits"/> is a subset of <paramref name="baseUnits"/>. + /// </summary> + /// <example>Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns <see cref="UnitInfo" /> for LengthUnit.Foot.</example> + /// <param name="quantityInfo">The quantity info.</param> + /// <param name="baseUnits">The <see cref="BaseUnits"/> to check against.</param> + /// <returns>The <see cref="UnitInfo"/> that has <see cref="BaseUnits"/> that is a subset of <paramref name="baseUnits"/>.</returns> + /// <exception cref="ArgumentNullException"><paramref name="baseUnits"/> is null.</exception> + /// <exception cref="InvalidOperationException">No unit was found that is a subset of <paramref name="baseUnits"/>.</exception> + /// <exception cref="InvalidOperationException">More than one unit was found that is a subset of <paramref name="baseUnits"/>.</exception> + public static UnitInfo GetUnitInfoFor(this QuantityInfo quantityInfo, BaseUnits baseUnits) + { + if (baseUnits is null) + throw new ArgumentNullException(nameof(baseUnits)); + + var matchingUnitInfos = GetUnitInfosFor(quantityInfo, baseUnits) + .Take(2) + .ToArray(); + + if (matchingUnitInfos.Length > 1) + throw new InvalidOperationException($"More than one unit was found that is a subset of {nameof(baseUnits)}"); + + UnitInfo? firstUnitInfo = matchingUnitInfos.FirstOrDefault(); + if (firstUnitInfo == null) + throw new InvalidOperationException($"No unit was found that is a subset of {nameof(baseUnits)}"); + + return firstUnitInfo; + } + +} diff --git a/UnitsNet.SI/UnitsNet.SI.csproj b/UnitsNet.SI/UnitsNet.SI.csproj new file mode 100644 index 0000000000..a7ee2a8407 --- /dev/null +++ b/UnitsNet.SI/UnitsNet.SI.csproj @@ -0,0 +1,59 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- NuGet properties --> + <PropertyGroup> + <PackageId>UnitsNet.SI</PackageId> + <Version>5.0.0-rc008</Version> + <Authors>Andreas Gullberg Larsen</Authors> + <Title>Units.NET - SI Unit System</Title> + <Description>Common types and abstractions that are required for the UnitsNet packages that adds quantities and units.</Description> + <Copyright>Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).</Copyright> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <RepositoryUrl>https://github.com/angularsen/UnitsNet</RepositoryUrl> + <PackageIcon>logo-32.png</PackageIcon> + <PackageIconUrl>https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png</PackageIconUrl> + <PackageProjectUrl>https://github.com/angularsen/UnitsNet</PackageProjectUrl> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> + <PackageTags>unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable</PackageTags> + <PackageReadmeFile>README.md</PackageReadmeFile> + </PropertyGroup> + + <!-- Assembly and msbuild properties --> + <PropertyGroup> + <AssemblyVersion>5.0.0.0</AssemblyVersion> <!-- Should reflect major part of Version --> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <RootNamespace>UnitsNet</RootNamespace> + <TargetFramework>netstandard2.0</TargetFramework> + </PropertyGroup> + + <!-- SourceLink --> + <PropertyGroup> + <PublishRepositoryUrl>true</PublishRepositoryUrl> + <EmbedUntrackedSources>true</EmbedUntrackedSources> + <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> + </PropertyGroup> + + <!-- Strong name signing --> + <PropertyGroup> + <AssemblyOriginatorKeyFile>../UnitsNet.snk</AssemblyOriginatorKeyFile> + <DelaySign>false</DelaySign> + <SignAssembly>true</SignAssembly> + </PropertyGroup> + + <!-- NuGet references that work for all TargetFrameworks, both signed and unsigned. --> + <ItemGroup> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" /> + </ItemGroup> + + <!-- Files to include in nuget package --> + <ItemGroup> + <None Include="../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> + <None Include="../README.md" Pack="true" PackagePath="/" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\UnitsNet.Core\UnitsNet.Core.csproj" /> + </ItemGroup> + +</Project> diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index bada53f7c8..d0614343ea 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -25,7 +25,7 @@ public HowMuch(double value, HowMuchUnit unit) public BaseDimensions Dimensions => BaseDimensions.Dimensionless; - public QuantityInfo QuantityInfo => new( + public static QuantityInfo Info => new( nameof(HowMuch), typeof(HowMuchUnit), new UnitInfo[] @@ -38,6 +38,8 @@ public HowMuch(double value, HowMuchUnit unit) Zero, BaseDimensions.Dimensionless); + public QuantityInfo QuantityInfo => Info; + public double As(Enum unit) => Convert.ToDouble(unit); public double As(UnitSystem unitSystem) => throw new NotImplementedException(); diff --git a/UnitsNet.Tests/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs deleted file mode 100644 index bd9f57c2e7..0000000000 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ /dev/null @@ -1,30 +0,0 @@ -#nullable enable -using System; - -namespace UnitsNet.Tests -{ - internal class DummyIQuantity : IQuantity - { - public BaseDimensions Dimensions => throw new NotImplementedException(); - - public QuantityInfo QuantityInfo => throw new NotImplementedException(); - - public Enum Unit => throw new NotImplementedException(); - - public QuantityValue Value => throw new NotImplementedException(); - - public double As(Enum unit ) => throw new NotImplementedException(); - - public double As(UnitSystem unitSystem ) => throw new NotImplementedException(); - - public string ToString(IFormatProvider? provider) => throw new NotImplementedException(); - - public string ToString(string? format, IFormatProvider? formatProvider) => throw new NotImplementedException(); - - public IQuantity ToUnit(Enum unit, UnitConverter unitConverter) => throw new NotImplementedException(); - - public IQuantity ToUnit(Enum unit ) => throw new NotImplementedException(); - - public IQuantity ToUnit(UnitSystem unitSystem ) => throw new NotImplementedException(); - } -} diff --git a/UnitsNet.Tests/QuantityTest.cs b/UnitsNet.Tests/QuantityTest.cs index 9642dd7fcb..139dae132b 100644 --- a/UnitsNet.Tests/QuantityTest.cs +++ b/UnitsNet.Tests/QuantityTest.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using UnitsNet.Tests.CustomQuantities; using UnitsNet.Units; using Xunit; @@ -135,7 +136,7 @@ public void TryFrom_GivenValueAndUnit_ReturnsQuantity() [Fact] public void TryParse_GivenInvalidQuantityType_ReturnsFalseAndNullQuantity() { - Assert.False(Quantity.TryParse(typeof(DummyIQuantity), "3.0 cm", out IQuantity? parsedLength)); + Assert.False(Quantity.TryParse(typeof(HowMuch), "3.0 cm", out IQuantity? parsedLength)); Assert.Null(parsedLength); } diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 67cd43b1de..193ec97855 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -24,7 +24,6 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="JetBrains.Annotations" Version="2022.1.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> diff --git a/UnitsNet.WindowsRuntimeComponent.sln.DotSettings b/UnitsNet.WindowsRuntimeComponent.sln.DotSettings deleted file mode 100644 index 0d4d747cc0..0000000000 --- a/UnitsNet.WindowsRuntimeComponent.sln.DotSettings +++ /dev/null @@ -1,8 +0,0 @@ -<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> - <s:Boolean x:Key="/Default/CodeInspection/CodeAnnotations/NamespacesWithAnnotations/=JetBrains_002EAnnotations/@EntryIndexedValue">True</s:Boolean> - <s:String x:Key="/Default/CodeStyle/CodeCleanup/Profiles/=Full/@EntryIndexedValue"><?xml version="1.0" encoding="utf-16"?><Profile name="Full"><CSUseVar><BehavourStyle>CAN_CHANGE_BOTH</BehavourStyle><LocalVariableStyle>IMPLICIT_WHEN_INITIALIZER_HAS_TYPE</LocalVariableStyle><ForeachVariableStyle>ALWAYS_EXPLICIT</ForeachVariableStyle></CSUseVar><CSUpdateFileHeader>True</CSUpdateFileHeader><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><CSReorderTypeMembers>True</CSReorderTypeMembers><CSRemoveCodeRedundancies>True</CSRemoveCodeRedundancies><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><HtmlReformatCode>True</HtmlReformatCode><CSArrangeThisQualifier>True</CSArrangeThisQualifier><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><JsInsertSemicolon>True</JsInsertSemicolon><JsReformatCode>True</JsReformatCode><JsFormatDocComments>True</JsFormatDocComments><CssAlphabetizeProperties>True</CssAlphabetizeProperties><CssReformatCode>True</CssReformatCode><XMLReformatCode>True</XMLReformatCode><VBOptimizeImports>True</VBOptimizeImports><VBShortenReferences>True</VBShortenReferences><VBReformatCode>True</VBReformatCode><VBFormatDocComments>True</VBFormatDocComments></Profile></s:String> - <s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForBuiltInTypes/@EntryValue">UseVarWhenEvident</s:String> - <s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForOtherTypes/@EntryValue">UseVarWhenEvident</s:String> - <s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForSimpleTypes/@EntryValue">UseVarWhenEvident</s:String> - <s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Licensed under MIT No Attribution, see LICENSE file at the root.
Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.</s:String> -</wpf:ResourceDictionary> diff --git a/UnitsNet.sln b/UnitsNet.sln index 2fc4b119a7..1fca4ae4ba 100644 --- a/UnitsNet.sln +++ b/UnitsNet.sln @@ -50,6 +50,32 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{71C6EF60 Build\init.ps1 = Build\init.ps1 EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Core", "UnitsNet.Core\UnitsNet.Core.csproj", "{BAB52BC4-D90E-4FFB-98F9-3BDB5BF83B99}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Length", "UnitsNet\UnitsNet.Length\UnitsNet.Length.csproj", "{6F9F6816-D724-4ADA-AAB2-AF9A3B993342}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Duration", "UnitsNet\UnitsNet.Duration\UnitsNet.Duration.csproj", "{7111F808-4468-453F-92F8-B5753922536D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.SI", "UnitsNet.SI\UnitsNet.SI.csproj", "{85AA41CE-0B76-4CFD-89BE-5DA951D6EF36}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.AmountOfSubstance", "UnitsNet\UnitsNet.AmountOfSubstance\UnitsNet.AmountOfSubstance.csproj", "{1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Duration", "UnitsNet\UnitsNet.Duration\UnitsNet.Duration.csproj", "{3C2AC54F-554C-518B-7C46-3B22D86D0E3B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.ElectricCurrent", "UnitsNet\UnitsNet.ElectricCurrent\UnitsNet.ElectricCurrent.csproj", "{55160A70-69B2-4144-B974-B64D78BD50E0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Length", "UnitsNet\UnitsNet.Length\UnitsNet.Length.csproj", "{0556C9AD-B3A1-730C-959F-BAF21E60F972}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.LuminousIntensity", "UnitsNet\UnitsNet.LuminousIntensity\UnitsNet.LuminousIntensity.csproj", "{733F9598-101B-936B-B081-2805DD793091}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Mass", "UnitsNet\UnitsNet.Mass\UnitsNet.Mass.csproj", "{F8C5A010-C353-31DA-CADC-B56186BE374F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Pressure", "UnitsNet\UnitsNet.Pressure\UnitsNet.Pressure.csproj", "{F907841F-B1EE-9B12-580E-CFE2324BED03}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Temperature", "UnitsNet\UnitsNet.Temperature\UnitsNet.Temperature.csproj", "{8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Core.Tests", "UnitsNet.Core.Tests\UnitsNet.Core.Tests.csproj", "{088CF8D6-E08E-4CA9-829A-AB48F6674535}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -88,6 +114,58 @@ Global {B4996AF5-9A8B-481A-9018-EC7F5B1605FF}.Debug|Any CPU.Build.0 = Debug|Any CPU {B4996AF5-9A8B-481A-9018-EC7F5B1605FF}.Release|Any CPU.ActiveCfg = Release|Any CPU {B4996AF5-9A8B-481A-9018-EC7F5B1605FF}.Release|Any CPU.Build.0 = Release|Any CPU + {BAB52BC4-D90E-4FFB-98F9-3BDB5BF83B99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BAB52BC4-D90E-4FFB-98F9-3BDB5BF83B99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BAB52BC4-D90E-4FFB-98F9-3BDB5BF83B99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BAB52BC4-D90E-4FFB-98F9-3BDB5BF83B99}.Release|Any CPU.Build.0 = Release|Any CPU + {6F9F6816-D724-4ADA-AAB2-AF9A3B993342}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F9F6816-D724-4ADA-AAB2-AF9A3B993342}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F9F6816-D724-4ADA-AAB2-AF9A3B993342}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F9F6816-D724-4ADA-AAB2-AF9A3B993342}.Release|Any CPU.Build.0 = Release|Any CPU + {7111F808-4468-453F-92F8-B5753922536D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7111F808-4468-453F-92F8-B5753922536D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7111F808-4468-453F-92F8-B5753922536D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7111F808-4468-453F-92F8-B5753922536D}.Release|Any CPU.Build.0 = Release|Any CPU + {85AA41CE-0B76-4CFD-89BE-5DA951D6EF36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85AA41CE-0B76-4CFD-89BE-5DA951D6EF36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85AA41CE-0B76-4CFD-89BE-5DA951D6EF36}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85AA41CE-0B76-4CFD-89BE-5DA951D6EF36}.Release|Any CPU.Build.0 = Release|Any CPU + {1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1CD282F3-3BDC-BC00-A63A-03A11A9B5C4D}.Release|Any CPU.Build.0 = Release|Any CPU + {3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3C2AC54F-554C-518B-7C46-3B22D86D0E3B}.Release|Any CPU.Build.0 = Release|Any CPU + {55160A70-69B2-4144-B974-B64D78BD50E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55160A70-69B2-4144-B974-B64D78BD50E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55160A70-69B2-4144-B974-B64D78BD50E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55160A70-69B2-4144-B974-B64D78BD50E0}.Release|Any CPU.Build.0 = Release|Any CPU + {0556C9AD-B3A1-730C-959F-BAF21E60F972}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0556C9AD-B3A1-730C-959F-BAF21E60F972}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0556C9AD-B3A1-730C-959F-BAF21E60F972}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0556C9AD-B3A1-730C-959F-BAF21E60F972}.Release|Any CPU.Build.0 = Release|Any CPU + {733F9598-101B-936B-B081-2805DD793091}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {733F9598-101B-936B-B081-2805DD793091}.Debug|Any CPU.Build.0 = Debug|Any CPU + {733F9598-101B-936B-B081-2805DD793091}.Release|Any CPU.ActiveCfg = Release|Any CPU + {733F9598-101B-936B-B081-2805DD793091}.Release|Any CPU.Build.0 = Release|Any CPU + {F8C5A010-C353-31DA-CADC-B56186BE374F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F8C5A010-C353-31DA-CADC-B56186BE374F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F8C5A010-C353-31DA-CADC-B56186BE374F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F8C5A010-C353-31DA-CADC-B56186BE374F}.Release|Any CPU.Build.0 = Release|Any CPU + {F907841F-B1EE-9B12-580E-CFE2324BED03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F907841F-B1EE-9B12-580E-CFE2324BED03}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F907841F-B1EE-9B12-580E-CFE2324BED03}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F907841F-B1EE-9B12-580E-CFE2324BED03}.Release|Any CPU.Build.0 = Release|Any CPU + {8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8BCE58B9-1A87-6BB3-3CEE-E0E0F012B618}.Release|Any CPU.Build.0 = Release|Any CPU + {088CF8D6-E08E-4CA9-829A-AB48F6674535}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {088CF8D6-E08E-4CA9-829A-AB48F6674535}.Debug|Any CPU.Build.0 = Debug|Any CPU + {088CF8D6-E08E-4CA9-829A-AB48F6674535}.Release|Any CPU.ActiveCfg = Release|Any CPU + {088CF8D6-E08E-4CA9-829A-AB48F6674535}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/UnitsNet/.gitignore b/UnitsNet/.gitignore deleted file mode 100644 index 0cae154d35..0000000000 --- a/UnitsNet/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/*project.lock.json diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index 71dcfc67d5..5eae2a2a55 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -121,6 +121,9 @@ public Acceleration(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AccelerationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index eea0e12d3b..15682df0ca 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -122,6 +122,9 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AmountOfSubstanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 6b68414b1f..38f5f23253 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -111,6 +111,9 @@ public AmplitudeRatio(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AmplitudeRatioUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index 61e25c4196..7d28789b92 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -123,6 +123,9 @@ public Angle(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AngleUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs index ce9917baa2..4fe07ca844 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs @@ -110,6 +110,9 @@ public ApparentEnergy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ApparentEnergyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs index 52e2285088..338d709746 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs @@ -111,6 +111,9 @@ public ApparentPower(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ApparentPowerUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index 0a00e2550f..b02871ac82 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -121,6 +121,9 @@ public Area(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AreaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index 6cbbe45cd7..31d0862188 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -110,6 +110,9 @@ public AreaDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AreaDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index d6577e5d30..d221eccef5 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -113,6 +113,9 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<AreaMomentOfInertiaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index 7d9029adba..fd2efe88e0 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -136,6 +136,9 @@ public BitRate(decimal value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<BitRateUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 2f349e2ecb..db0fb18e27 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -110,6 +110,9 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<BrakeSpecificFuelConsumptionUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs index cccf254368..018a1b016c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs @@ -117,6 +117,9 @@ public Capacitance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<CapacitanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index 3e75018447..15e3083a4e 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -110,6 +110,9 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<CoefficientOfThermalExpansionUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs index e965366524..d728a6a07f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs @@ -114,6 +114,9 @@ public Compressibility(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<CompressibilityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 6196ea3180..3a6143127f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -161,6 +161,9 @@ public Density(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<DensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index 36ef64fed4..fa3e11c13e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -118,6 +118,9 @@ public Duration(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<DurationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index 7341186c46..bb8844a750 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -120,6 +120,9 @@ public DynamicViscosity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<DynamicViscosityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index 4c37320694..9cc7879aa1 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -111,6 +111,9 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricAdmittanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index 22a34c7766..0465f521d0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -115,6 +115,9 @@ public ElectricCharge(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricChargeUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index 8c93da965a..df95a43c12 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -111,6 +111,9 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricChargeDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index 8e1c71f938..97d2baae9f 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -113,6 +113,9 @@ public ElectricConductance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricConductanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index 5dee91d567..8ac53fc99c 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -116,6 +116,9 @@ public ElectricConductivity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricConductivityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index 7dc5fbfa3b..e5dcb9dafd 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -115,6 +115,9 @@ public ElectricCurrent(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricCurrentUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index 2a0d07c524..78af2540b9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -113,6 +113,9 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricCurrentDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index 40d2ce444b..9f83233172 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -111,6 +111,9 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricCurrentGradientUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index 7809de6fe8..a6430c3b4f 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -111,6 +111,9 @@ public ElectricField(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricFieldUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index 5ed2447816..47b6d6a281 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -114,6 +114,9 @@ public ElectricInductance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricInductanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index 041b123462..01debb1de0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -112,6 +112,9 @@ public ElectricPotential(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricPotentialUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs index 2f4e5a6dcc..866de35b9a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs @@ -112,6 +112,9 @@ public ElectricPotentialAc(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricPotentialAcUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index 4f3a640775..23906c6875 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -127,6 +127,9 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricPotentialChangeRateUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs index a2bd0b9f52..b76cd5c0ef 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs @@ -112,6 +112,9 @@ public ElectricPotentialDc(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricPotentialDcUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 0895f8712c..4a57f8b4fe 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -113,6 +113,9 @@ public ElectricResistance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricResistanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index 28116b891b..131849719f 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -124,6 +124,9 @@ public ElectricResistivity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricResistivityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index 1400483cea..c2f1e3862e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -113,6 +113,9 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ElectricSurfaceChargeDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index 12bc85d96d..b227180f16 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -145,6 +145,9 @@ public Energy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<EnergyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs index d6fddeeb95..4a67d93e08 100644 --- a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs @@ -119,6 +119,9 @@ public EnergyDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<EnergyDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index 4d0a45b92b..d8c3c95d97 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -114,6 +114,9 @@ public Entropy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<EntropyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index b5d6412ea5..52049f0325 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -122,6 +122,9 @@ public Force(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ForceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index ad41cfec24..c1ccb82494 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -122,6 +122,9 @@ public ForceChangeRate(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ForceChangeRateUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index c128f3a3a2..b0330768c2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -145,6 +145,9 @@ public ForcePerLength(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ForcePerLengthUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index 54cd92d566..6bb509b8ff 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -118,6 +118,9 @@ public Frequency(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<FrequencyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs index 75d1adc22f..82c50306a9 100644 --- a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -114,6 +114,9 @@ public FuelEfficiency(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<FuelEfficiencyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs index 9f99cfbdb8..0f8718fbd5 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs @@ -125,6 +125,9 @@ public HeatFlux(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<HeatFluxUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index 9d3d8c4480..cc2a394cd3 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -110,6 +110,9 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<HeatTransferCoefficientUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index 523809d34c..d2c44c3d2a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -114,6 +114,9 @@ public Illuminance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<IlluminanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index 39a3cdf603..87b349331a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -133,6 +133,9 @@ public Information(decimal value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<InformationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index a00a5a4540..b1e4688bc4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -121,6 +121,9 @@ public Irradiance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<IrradianceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index 755337d54e..36463fb155 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -117,6 +117,9 @@ public Irradiation(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<IrradiationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs index eab9fe53f3..1eb90a0026 100644 --- a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs @@ -118,6 +118,9 @@ public Jerk(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<JerkUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index 583f0f686d..dcc686ce69 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -119,6 +119,9 @@ public KinematicViscosity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<KinematicViscosityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index 4c5c7a0e49..e14f8375ee 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -143,6 +143,9 @@ public Length(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LengthUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index 846bc45761..801faf9260 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -109,6 +109,9 @@ public Level(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LevelUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index f15e3c0dc7..6af67124c9 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -124,6 +124,9 @@ public LinearDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LinearDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs index 0ced684151..f848cd389c 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -135,6 +135,9 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LinearPowerDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs index b39f3831c3..3927aed0c6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs @@ -120,6 +120,9 @@ public Luminance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LuminanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs index ae66d5357b..2d7d5bf6de 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs @@ -124,6 +124,9 @@ public Luminosity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LuminosityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index 9df0e7c9ae..e4a15ed25a 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -111,6 +111,9 @@ public LuminousFlux(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LuminousFluxUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index 20b08ec117..0c47bec372 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -111,6 +111,9 @@ public LuminousIntensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<LuminousIntensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index e19c887bbe..1f63135f65 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -116,6 +116,9 @@ public MagneticField(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MagneticFieldUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index 066d1e08d7..c61d8be04c 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -111,6 +111,9 @@ public MagneticFlux(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MagneticFluxUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index c81155fc68..c8218c6489 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -111,6 +111,9 @@ public Magnetization(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MagnetizationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index de6ac8cc93..88630e648e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -132,6 +132,9 @@ public Mass(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MassUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs index 44a6ab7971..12f4eceea0 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs @@ -159,6 +159,9 @@ public MassConcentration(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MassConcentrationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index 165e72c773..051b73046c 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -140,6 +140,9 @@ public MassFlow(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MassFlowUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index f86bf3cd4b..7424bd38d4 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -119,6 +119,9 @@ public MassFlux(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MassFluxUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs index 692b663a59..8f7706e480 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs @@ -134,6 +134,9 @@ public MassFraction(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MassFractionUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index 3c22f92d29..70b6990101 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -135,6 +135,9 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MassMomentOfInertiaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index 9b4fff4499..85d53ef75b 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -110,6 +110,9 @@ public MolarEnergy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MolarEnergyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index 8e8af45d68..51a8f100e9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -110,6 +110,9 @@ public MolarEntropy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MolarEntropyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index d913a73db4..169a43295d 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -119,6 +119,9 @@ public MolarMass(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MolarMassUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index 5244c4abd9..d9b71ae149 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -119,6 +119,9 @@ public Molarity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<MolarityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index 616d8732b5..b71d480140 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -111,6 +111,9 @@ public Permeability(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PermeabilityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index 5bb66d8565..a650dda573 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -111,6 +111,9 @@ public Permittivity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PermittivityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs index b6b662e970..55cf52d687 100644 --- a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs @@ -115,6 +115,9 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PorousMediumPermeabilityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index f6dbf7cd16..7fc423d28f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -133,6 +133,9 @@ public Power(decimal value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PowerUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs index e2d2a7cea8..c074074dc1 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs @@ -151,6 +151,9 @@ public PowerDensity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PowerDensityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index 8f186f63cf..9fdf8a0af2 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -109,6 +109,9 @@ public PowerRatio(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PowerRatioUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 54411b8a29..5b1bc6b741 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -154,6 +154,9 @@ public Pressure(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PressureUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index aaba7fa985..58374ad90f 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -121,6 +121,9 @@ public PressureChangeRate(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<PressureChangeRateUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index ac1ac8ea12..4411228eda 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -113,6 +113,9 @@ public Ratio(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RatioUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs index 336b7f5e8d..6188011a4a 100644 --- a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -109,6 +109,9 @@ public RatioChangeRate(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RatioChangeRateUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs index 5657a371a7..249b1c0e02 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs @@ -110,6 +110,9 @@ public ReactiveEnergy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ReactiveEnergyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs index af253aff02..a0cdedc524 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs @@ -111,6 +111,9 @@ public ReactivePower(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ReactivePowerUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs index 53b5dc4462..b99635e09e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -121,6 +121,9 @@ public ReciprocalArea(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ReciprocalAreaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs index 37f0e3bd9e..3a65e3ad8b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -120,6 +120,9 @@ public ReciprocalLength(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ReciprocalLengthUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs index ce1899c085..0bef882634 100644 --- a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -108,6 +108,9 @@ public RelativeHumidity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RelativeHumidityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index 71174e3415..7b0718005e 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -111,6 +111,9 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RotationalAccelerationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index 57b4e06716..5b4fc70470 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -120,6 +120,9 @@ public RotationalSpeed(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RotationalSpeedUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs index 8ee0f934a1..0d990352fd 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -140,6 +140,9 @@ public RotationalStiffness(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RotationalStiffnessUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index 6fc4666df4..d9727a124b 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -112,6 +112,9 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<RotationalStiffnessPerLengthUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs index 8b69e08206..cc567a3e56 100644 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs @@ -108,6 +108,9 @@ public Scalar(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ScalarUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index ca62ba4ad7..58c46ea150 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -111,6 +111,9 @@ public SolidAngle(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SolidAngleUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index dab35a073e..76c02f3821 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -139,6 +139,9 @@ public SpecificEnergy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SpecificEnergyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index 2a437caa79..5b53b82e20 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -116,6 +116,9 @@ public SpecificEntropy(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SpecificEntropyUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index 6af1748861..c166f31dd1 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -114,6 +114,9 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SpecificFuelConsumptionUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index fc30c9f17b..688488e3d0 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -110,6 +110,9 @@ public SpecificVolume(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SpecificVolumeUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index b799174065..1bca5643bf 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -127,6 +127,9 @@ public SpecificWeight(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SpecificWeightUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index 849bb89906..d995b3b291 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -140,6 +140,9 @@ public Speed(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<SpeedUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index 8c959aba7e..e179476330 100644 --- a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -116,6 +116,9 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<StandardVolumeFlowUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index 7b5ee2cff0..252003a195 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -117,6 +117,9 @@ public Temperature(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TemperatureUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index 24ada2aa55..8b9c855a08 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -117,6 +117,9 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TemperatureChangeRateUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index a9a16c623c..e37c065936 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -116,6 +116,9 @@ public TemperatureDelta(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TemperatureDeltaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs index e5b0bc8fae..c95e22844d 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -111,6 +111,9 @@ public TemperatureGradient(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TemperatureGradientUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index 7b86af441d..214992128e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -112,6 +112,9 @@ public ThermalConductivity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ThermalConductivityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs index 376a155418..453f50d45e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -113,6 +113,9 @@ public ThermalResistance(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ThermalResistanceUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index a147e43adc..4706d79bb6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -132,6 +132,9 @@ public Torque(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TorqueUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs index 8368c55b96..550f54c637 100644 --- a/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TorquePerLength.g.cs @@ -128,6 +128,9 @@ public TorquePerLength(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TorquePerLengthUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs index 52990e4c03..de571303e2 100644 --- a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs @@ -111,6 +111,9 @@ public Turbidity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<TurbidityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index 87629b7519..9839ffb278 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -108,6 +108,9 @@ public VitaminA(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VitaminAUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index ebecd9d997..bb5e64cac5 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -160,6 +160,9 @@ public Volume(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VolumeUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs index e37c38c961..a426bfd4ff 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -130,6 +130,9 @@ public VolumeConcentration(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VolumeConcentrationUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index 7fe1f66710..2a88338ada 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -169,6 +169,9 @@ public VolumeFlow(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VolumeFlowUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index 15ebfb4113..6255701277 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -109,6 +109,9 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VolumeFlowPerAreaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs index 79fb39776b..b14e2f3a01 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -114,6 +114,9 @@ public VolumePerLength(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VolumePerLengthUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index e2b8beeec4..6904ff7fdd 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -119,6 +119,9 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<VolumetricHeatCapacityUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index f57ed756cc..244291a0f5 100644 --- a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -113,6 +113,9 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<WarpingMomentOfInertiaUnit> Info { get; } + /// <inheritdoc cref="IQuantity.QuantityInfo"/> + static QuantityInfo IQuantity.Info => Info; + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> diff --git a/UnitsNet/IArithmeticQuantity.cs b/UnitsNet/IArithmeticQuantity.cs index 7e9ce19b06..1e60697fa8 100644 --- a/UnitsNet/IArithmeticQuantity.cs +++ b/UnitsNet/IArithmeticQuantity.cs @@ -28,10 +28,4 @@ public interface IArithmeticQuantity<TSelf, TUnitType, TValueType> : IQuantity<T , INumber<TValueType> #endif { -#if NET7_0_OR_GREATER - /// <summary> - /// The zero value of this quantity. - /// </summary> - static abstract TSelf Zero { get; } -#endif } diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 1ea0530d90..3012cb361a 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -15,6 +15,13 @@ namespace UnitsNet /// </summary> public interface IQuantity : IFormattable { +#if NET7_0_OR_GREATER + /// <summary> + /// The zero value of this quantity. + /// </summary> + static abstract QuantityInfo Info { get; } +#endif + /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> @@ -132,5 +139,11 @@ public interface IQuantity<TSelf, TUnitType, TValueType> : IQuantity<TUnitType> where TUnitType : Enum where TValueType : struct { +#if NET7_0_OR_GREATER + /// <summary> + /// The zero value of this quantity. + /// </summary> + static abstract TSelf Zero { get; } +#endif } } diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index 50e3817251..b6d91a8de8 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -64,5 +64,9 @@ <None Include="../Docs/Images/logo-32.png" Pack="true" PackagePath="/" /> <None Include="../README.md" Pack="true" PackagePath="/" /> </ItemGroup> + <ItemGroup> + <!-- TODO Add me back --> +<!-- <ProjectReference Include="..\UnitsNet.Core\UnitsNet.Core.csproj" />--> + </ItemGroup> </Project>